【问题标题】:Why is Ruby's splat slower when combining arrays than using + to combine arrays?为什么组合数组时 Ruby 的 splat 比使用 + 组合数组时更慢?
【发布时间】: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


【解决方案1】:

为什么一个标准库或核心功能比另一个慢?
因为它取决于提供给它的类型和/或数据。

Splat 并不总是与数组有关。它可以采用nil 并将其作为空数组处理——在这里您已经有了一些条件行为,而数组的连接不是条件的,而是直接的。

【讨论】:

    猜你喜欢
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多