lua-users home
lua-l archive

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


Hi,

Philippe Lhoste wrote:
> 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?

There is no difference in memory efficiency. Either way the space
for r (one stack slot) is needed only once. There is no heap
allocation going on.

Declaring a variable inside a scope is a good idea anyway:
- The variable does not inadvertently leak from the scope.
- The occupied stack slot is recycled after the end of the scope.
- Combining declaration and initialization helps to avoid many
  common errors.

It's also slightly faster in this case, because the function
result does not need to be copied around one more time (look at
the bytecode). But this is really an implementation detail.

In case of doubt opt for clarity. Try to combine declaration and
initialization. Do not reuse variables for different purposes (or
even different types). Stack slots are cheap, programmer time is
not. And it would be easy for an optimizing compiler to do life
time analysis and act accordingly.

IMHO the following is perfectly ok (with proper variable names!):

  local a,b = string.match(x, "some-regexp")
  if a then return ... end
  local c,d,e = string.match(x, "another-regexp")
  if c then return ... end
  local f,g = string.match(x, "yet-another-regexp")
  if f then return ... end

Trying to reuse a and b does not buy you anything here.

Bye,
     Mike