[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Basic speed optimization question
- From: Rici Lake <lua@...>
- Date: Sat, 30 Dec 2006 21:21:07 -0500
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 = MyObject.new();
for(...)
{
// 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)
end
Would it be better Lua programming (in terms of *speed* optimization)
to do directly:
for
local a = ... -- because here the variable 'a' is local and not
'non-local', thus very quickly resolved (indexed) even if recreated at
each loop
end
Thank you for your thoughts and comments about it!
Genio
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
end
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
end
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.
end