首页 > 解决方案 > Lua:如何有效地乘以由数字组成的一维表中的所有元素

问题描述

假设我们有一个名为 的 Lua 表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迭代器。)

我的问题:

标签: algorithmluamultiplication

解决方案


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和基于它的各种数字框架:123。此外,还有语言作者关于优化的文章。


推荐阅读