Suppose that we have a Lua table called t
, defined as follows:
t = {4, 5, 6, 7}
Suppose we wish further to know what the product of the numbers in t
is. (Aside: the answer is 840
.) I can think of two methods.
First, a basic for
loop:
answer = 1
for i = 1, #t do
answer = answer * t[i]
end
print ( answer )
Second, an ipairs
iterator:
answer = 1
for i, j in ipairs ( t ) do
answer = answer * j
end
print ( answer )
(I suppose one could also use a pairs
iterator.)
My questions:
answer
that are more efficient and/or robust than the methods shown above?ipairs
involves a function call. This makes generic for-loop slower tiny bit. If the inner task is anything complex, the function call overhead will be negligible, in comparison to a few arithmetic operations it may be notable in some extreme cases. Try it:
a={}
for i=1,2e8 do a[i]=math.random() end
t=os.time()
q=1
for i=1,#a do q=q*a[i] end
print(os.time()-t)
w=1
t=os.time()
for i,v in ipairs(a) do w=w*v end
print(os.time()-t)
For me results were 15
and 18
.
It is more impactful when the calculation is repeated multiple times (nested loops):
a={} for i=1,1e4 do a[i]=math.random() end
t=os.time() q=1; for i=1,1e5 do for j=1,1e4 do q=q*a[j] end end print(os.time()-t)
t=os.time() q=1; for i=1,1e5 do for _,v in ipairs(a) do q=q*v end end print(os.time()-t)
But still not a lot.
If you really need to squeeze out even that bit of performance, you probably should take a look at luajit and various numeric frameworks based on it: 1, 2, 3. Also, there's article on optimization by the language author.