lua-users home
lua-l archive

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


On 18/09/2011 14.31, HyperHacker wrote:
[...]

I thought the point of moving locals out of a loop/function was to
reduce lookups and create closures, e.g. doing "local floor =
math.floor" before a loop prevents having to look up 'math' in _G and
'floor' in math every iteration.

Well that is also a use case.

BTW. I reread the manual (5.1.4). Near the end of section 2.6 there is (emphasis mine):

"Notice that *each execution of a local statement defines new local variables*. Consider the following example:

     a = {}
     local x = 20
     for i=1,10 do
       local y = 0
       a[i] = function () y=y+1; return x+y end
     end

The loop creates ten closures (that is, ten instances of the anonymous function). *Each of these closures uses a different y variable*, while all of them share the same x."


Therefore it seems that I remembered well:

local e

has a runtime effect, that can be used to generate different upvalues for different closures.

But my doubt was about my apparently wrong attempt at optimizing this potential time overhead, which is based on the assumption that "local e" takes some time when it is executed. Therefore, when there is no reason to create a new local, pulling its declaration out of the loop could save some cycles [1]. So, according to that reasoning:

local e
for ... do
  e = init_exp
  --use e
end

should be faster than

for ... do
  local e
  e = init_exp
  -- use e
end


since "local e" is executed only once.

I still don't understand what's wrong in my reasoning, since the implementation clearly proves me wrong as I showed in my first post.

-- Lorenzo


[1] I know these examples are trivial and not worth being optimized, but the savings could be greater if the locals pulled out are in a nested loop. And besides that there is the point of understanding what's going on and why my reasoning is wrong.