lua-users home
lua-l archive

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


On Tue, 2009-06-16 at 23:22 +0100, Peter Cawley wrote:
> On Tue, Jun 16, 2009 at 10:38 PM, Norbert Kiesel<nkiesel@tbdnetworks.com> wrote:
> > Hi,
> >
> > is there any real difference between
> >
> > local a = foo()
> > -- use a
> > local a = bar()
> > -- use a
> You are declaring two separate variables, albeit with the same name.
> You are correct in that it generates shorter bytecode, but only by a
> single move instruction. As for the reason why, the code generator
> uses scratch space for a function call, and when declaring a new
> variable, it so happens that the new variable occupies the same
> position as the scratch used for the return value, and hence doesn't
> have to move it to the final location. Other language constructs can
> put the result directly into the correct location, so the following
> two would gain nothing from the extra "local" statement:
> 
> local a = 4
> -- ...
> local a = 5
> -- ...
> 
> local a = p[q]
> -- ...
> local a = r[s]
> -- ...
> 
> The time saved by avoiding a single move instruction is negligible, so
> I wouldn't consider it worthwhile. There are considerable
> disadvantages to redeclaring locals in this way though:
> 
> 1) As you are declaring two separate variables, they bind as upvalues
> separately, as shown in the following example:
> 
> local a = foo()
> function GetA() return a end
> local a = bar()
> print(GetA()) --> prints the result of foo, not bar
> 
> 2) As there are now multiple variables where there were once one, the
> function will have a larger stack size, which will ever so slightly
> increase the time taken to call the function, slightly increase the
> memory required to parse and store the function, and (especially if
> called recursively) slightly increase memory usage while executing.
> These increases are all ever so slight, but then the avoidance of a
> single move instruction is the ever so slight advantage in favour.

Thanks for the nice explanation.  The place where I'm using this right
now is that I have a set of lua scripts that are constructed using
copy-n-paste of templates.  Something along these lines

local result = ''

local a, b = foo("bla bla")
... process a,b, append to overall result
result = result ..
 
local a, b = foo("rabarber rabarber")
... process a,b, append to overall result
result = result ..

report(result)

A typical script has between 1 and 5 of these blocks, and foo() talks to
another device and thus is really slow compared to the rest of the code.
So far I was always removing the "local" in front of all but the first
template.  Just wanted to make sure I don't do something stupid here by
leaving it.

</nk>