algorithm - 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
迭代器。)
我的问题:
- 上面显示的两种方法中的任何一种都存在任何真正的缺点吗?
answer
是否有比上述方法更有效和/或更稳健的方法来获得所需值?
解决方案
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)
对我来说结果是15
和18
。多次重复计算(嵌套循环)时影响更大:
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和基于它的各种数字框架:1、2、3。此外,还有语言作者关于优化的文章。
推荐阅读
- vb.net - 列表框的粗体/重新着色所选项目(VB.NET)
- gradle - 使用 gradle 从 Nexus 获取 oracle JDBC jar
- ruby-on-rails - 不能使用 rake db:migrate
- jquery - 有两个事件监听器,如果一个被调用,那么另一个不应被调用
- xcode - xcode 9中的Apple Mach-O链接器错误
- android - “Android.Runtime.JavaProxyThrowable'被抛出”在后台长时间恢复时
- ios - 二元运算符不能应用于 Int 和 String 类型的操作数 - Swift 2.3 -> Swift 3.2 转换错误
- sql - SQL:将 nvarchar 值“XXX”转换为数据类型 int 时转换失败
- automated-tests - UFT 在多个实例中执行应用程序
- javascript - 我无法在计算器的 num1 参数中添加两个字符