lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi all!

Till now I believed that pulling out local definitions from loops would improve performance of Lua code. Please compare this trivial example:

----------------------------------
local function f1( array )
   local e
   for i = 1, #array do
      e = array[ i ]
      print( e )
   end
end

local function f2( array )
   for i = 1, #array do
      local e = array[ i ]
      print( e )
   end
end
----------------------------------

I would have said that f1 was faster than f2 because in f2 the "local" statement was executed every time, since Lua doesn't do almost any kind of optimization when compiling.

But recently by chance I compared the "disassembled code" for those two functions, and they look almost the same to me (the case was more complex, with more locals - I stripped it down to reduce clutter here):


function <lua_scratchpad9.lua:1,7> (10 instructions, 40 bytes at 003D4510)
1 param, 8 slots, 0 upvalues, 6 locals, 2 constants, 0 functions
	1	[3]	LOADK    	2 -1	; 1
	2	[3]	LEN      	3 0
	3	[3]	LOADK    	4 -1	; 1
	4	[3]	FORPREP  	2 4	; to 9
	5	[4]	GETTABLE 	1 0 5
	6	[5]	GETGLOBAL	6 -2	; print
	7	[5]	MOVE     	7 1
	8	[5]	CALL     	6 2 1
	9	[3]	FORLOOP  	2 -5	; to 5
	10	[7]	RETURN   	0 1

function <lua_scratchpad9.lua:9,14> (10 instructions, 40 bytes at 003D4CB0)
1 param, 8 slots, 0 upvalues, 6 locals, 2 constants, 0 functions
	1	[10]	LOADK    	1 -1	; 1
	2	[10]	LEN      	2 0
	3	[10]	LOADK    	3 -1	; 1
	4	[10]	FORPREP  	1 4	; to 9
	5	[11]	GETTABLE 	5 0 4
	6	[12]	GETGLOBAL	6 -2	; print
	7	[12]	MOVE     	7 5
	8	[12]	CALL     	6 2 1
	9	[10]	FORLOOP  	1 -5	; to 5
	10	[14]	RETURN   	0 1


For readability and for scope minimization I would like to use the style of f2, but I learned to use the style of f1 (predeclaring all the temporary locals used in the loop) when performance could be at stake.

I cannot trace back where first I learned to do that, but I fear now I have interpreted wrongly some optimization tip. I reread Roberto's Lua Gem chapter on optimization and the optimization-related pages on the WIKI, but nowhere I could find support for that approach. Therefore I'm beginning to suspect I was acting under a false belief.

Am I missing something (I'm not an expert of Lua VM so I may have missed something related to the meaning of the instructions operands in the listings above)?

Any clarification or pointer appreciated!
TIA

-- Lorenzo