lua-users home
lua-l archive

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


From:	lua-bounces@bazar2.conectiva.com.br on behalf of Philippe Lhoste
> Does this mean that:
>
> local t = ''
> repeat
>	local r = math.random(1, 50)
>	t = t .. " " .. r
> until (string.len(t) > 100)
> print(t)
>
> is less efficient than declaring the local r outside the loop?
> At least in terms of memory?

I think so, and in speed (minorly). Just yesterday I wrote code that auto-converted XEXPR XML into Lua code, and the result (at first) was something like this:

local tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7 --and on and on

tmp1 = 1
_G[ "foo" ] = tmp1
tmp2 = 0
_G[ "bar" ] = tmp2
tmp3 = tmp2 < tmp1
if tmp3 then
   tmp4 = "Hello "
   tmp5 = "World"
   tmp6 = tmp4 .. tmp5
   print( tmp6 )
end

Then I 'fixed' my converter to re-use variables no longer in use. The above changed to something like:

local tmp1, tmp2, tmp3
tmp1 = 1
_G[ "foo" ] = tmp1
tmp2 = 0
_G[ "bar" ] = tmp2
tmp3 = tmp2 < tmp1
if tmp3 then
   tmp1 = "Hello "
   tmp2 = "World"
   tmp3 = tmp1 .. tmp2
   print( tmp3 )
end

The test output went from 37 distinct local variables to 6, which I thought was a good thing...but over 100,000 iterations my run speed *decreased* by 2%. I guess that re-using the variables meant that a lot more values were freed up for GC, more often.

<<winmail.dat>>