lua-users home
lua-l archive

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

On 30-Dec-06, at 9:07 PM, Aladdin Lampé wrote:

Hi all,

In other programming languages, I used to declare objects before loops in order not to re-create one at each loop, for instance in Java :
MyObject hello =;
// use and reuse 'hello' here, without the overhead of recreating the object at each loop

In Lua, I often do the same:
local a = ""
for ...
a = ... -- use variable a, change its value, etc. (here variable 'a' is 'non-local' thus with no indexed search)

Would it be better Lua programming (in terms of *speed* optimization) to do directly:
local a = ... -- because here the variable 'a' is local and not 'non-local', thus very quickly resolved (indexed) even if recreated at each loop

Thank you for your thoughts and comments about it!

You'll find it quicker (and, imho, more readable) to use the second idiom, particularly if the variable is being assigned to the result of a function call.

In any event, no "object" is created by declaring a variable local. In
the usage:

local a = ""
for i, w in ipairs(t) do
  a = "(" .. w .. ")"
  -- do something with a

The initial string assigned to a is simply thrown away when a is reassigned. So you're not saving anything; all you're doing is
needlessly assigning a to the empty string (which doesn't use up
much time, since the string already exists).

On the other hand, if the usage were:

local a, b
for i, w in ipairs(t) do
  a, b = w:match"(%a*)(%d*)"
  -- do something with a and b

you'll end up incurring two VM move operations in each loop, which
could be avoided by the more natural:

for i, w in ipairs(t) do
  local letters, digits = w:match"(%a*)(%d*)"
  -- do something, etc.