【发布时间】:2016-10-19 16:16:09
【问题描述】:
我做了一个疯狂的猜测,将一个数组添加到另一个数组中会比将两个数组相加更快,但在快速基准测试后我发现我错了。我假设解释器只会将 splat 转换为数组文字,而不必每次都对其调用 + 方法。那么,为什么+ 比 splat 快?
我使用了这个基准代码:
def test(trials = 1000)
head = [1,2,3]
tail = 100.times.to_a
t = Time.now.to_f
trials.times do |i|
a = [head, *tail]
end
puts "splat done in #{Time.now.to_f - t}"
t = Time.now.to_f
trials.times do |i|
a = head + tail
end
puts "+ done in #{Time.now.to_f - t}"
end
我得到了这个结果:
2.2.5 :059 > test
splat done in 0.001013040542602539
+ done in 0.0009138584136962891
增加试验:
2.2.5 :061 > test 1_000_000
splat done in 0.5123062133789062
+ done in 0.4400749206542969
它非常接近,但始终稍快。
【问题讨论】:
-
不清楚您所说的“将 splat 转换为数组文字并且不必每次都调用 + 方法”是什么意思。
-
@sawa 说你有
stuff = [1,2]我认为它可能会用[1, 2, 3]替换[1, *stuff],因此将一些方法调用保存到+或其他东西,但不确定。 -
我认为 benchmark-ips 会比时间差更好更准确
-
好吧 benchmark-ips 确认 splat 比较慢,我想知道为什么:O
-
@Sculper 顺便说一句,benchmark-ips 将两个版本显示为与 rubinius 的“相同”:O
标签: ruby performance