lua-users home
lua-l archive

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


Lorenzo Donati <lorenzodonatibz@interfree.it> writes:

> Till now I believed that pulling out local definitions from loops
> would improve performance of Lua code.

Why would it do that?

> 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.

Uh what? "local e" is a declaration.  It does not generate code but is
merely executed in the compiler.  And Lua does not recompile a loop for
every iteration.  That would be stupid.

> 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):

> 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 guess so.  It is rather the other way round.  By importing variables
into blocks, you run the risk of getting upvalues.

> 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)?

You are missing something.  local x does not generate code, it merely
tells the compiler something about how to generate code.  local x =
expr, in contrast, also has a runtime component.  It will reevaluate the
expression every time you run over that code when looping.  It will not
rethink the scoping, however.

-- 
David Kastrup