Lua:如何高效地乘以由数字组成的一维 table 中的所有元素

Lua: How to multiply -- efficiently -- all elements in a 1-dimensional table consisting of numbers

假设我们有一个Luatable叫t,定义如下:

t = {4, 5, 6, 7}

假设我们想进一步知道t中数字的乘积是多少。 (旁白:答案是840。)我可以想到两种方法。

首先,一个基本的 for 循环:

answer = 1
for i = 1, #t do
   answer = answer * t[i]
end
print ( answer )

其次,一个ipairs迭代器:

answer = 1 
for i, j in ipairs ( t ) do
   answer = answer * j
end
print ( answer )

(我想也可以使用 pairs 迭代器。)

我的问题:

ipairs涉及函数调用。这使得通用 for 循环变慢了一点点。如果内部任务很复杂,函数调用的开销可以忽略不计,与一些算术运算相比,在某些极端情况下它可能会很明显。试试看:

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)

对我来说,结果是 1518。 当多次重复计算(嵌套循环)时影响更大:

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)

但还是不多。

如果您真的需要挤出一点性能,您可能应该看看 luajit and various numeric frameworks based on it: 1, 2, 3。 此外,还有 article 语言作者的优化。