[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: simple local variables question
- From: Peter Cawley <lua@...>
- Date: Tue, 16 Jun 2009 23:22:35 +0100
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.