View Single Post
07-06-12, 05:40 PM   #1
Haleth
This Space For Rent
 
Haleth's Avatar
Featured
Join Date: Sep 2008
Posts: 1,173
A question on memory allocation/access

I'm wondering a couple of things about lua, some of them specific to WoW (I think), that have been bothering me for a while.

1. Take this example code:

Code:
local function myFunction()
	local name = GetSomeName()
	-- do other things
end
Assume the function is used multiple times. Is this any less efficient than:

Code:
local name
local function myFunction()
	name = GetSomeName()
	-- do other things
end
I assume that in the first case, a new variable is allocated each time the function runs. But is it cleared up as soon as the function finishes, perhaps by an automatic garbage collector? Otherwise, the second example (using the same variable and simply changing its content) would be more efficient, right?

2. A similar example (assume this function is called multiple times as well):

Code:
local function myFunction()
	myFrame:SetScript("OnUpdate", function()
		-- do things
	end)
	-- do other things
	myFrame:SetScript("OnUpdate", nil)
end
Is this less efficient than:

Code:
local function onUpdate()
	-- do things
end

local function myFunction()
	myFrame:SetScript("OnUpdate", onUpdate)
	-- do other things
	myFrame:SetScript("OnUpdate", nil)
end
3. In for-loops, if your end condition is the return value of a function, does the loop run this function on every cycle to compare the current index against it or is the return value stored at the start of the loop? In other words, is this:

Code:
local myNumber = GetSomeNumberFromServer()
for i = 1, myNumber do
	-- do things
end
More efficient than this:

Code:
for i = 1, GetSomeNumberFromServer() do
	-- do things
end
4. I know that importing global variables (such as _G) into your code can speed things up a tiny tiny bit when you use them often. But how is this? If I'm correct, tables are passed by reference. How would creating an other reference which is the same as the existing one make things any faster?

Thanks!

Last edited by Haleth : 07-06-12 at 05:47 PM.
  Reply With Quote