为什么Array.reverse_each比Array.reverse.each更快

sai*_*ala 16 ruby arrays

我几乎不使用reverse_each方法,而是在reverse.each需要向后遍历数组时调用.所以我只做了一些基准测试,显然reverse_each速度明显快于reverse.each.

  • 这是因为在使用时,在迭代数组之前有一个与创建反向数组相关的时间元素reverse.each吗?

然而,在我的示例(下面)中,TIME(reverse) + TIME(each) - TIME(reverse.each) ~ 1.2 seconds对于大小为4的数组,进行了1000万次迭代.无论数组的大小如何,这个时间差都或多或少保持稳定.我已经测试了多达100个元素.

  • 这一秒差异的原因是什么?

require 'benchmark'

number = 10000000
arr = (1..4).to_a

Benchmark.bm(13) do |x|
    x.report("reverse.each") { number.times { arr.reverse.each {|x| x} } }
    x.report("reverse_each") { number.times { arr.reverse_each {|x| x} } }
    x.report("reverse")      { number.times { arr.reverse } }             
    x.report("each")         { number.times { arr.each {|x| x} } }        
end
Run Code Online (Sandbox Code Playgroud)

apn*_*ing 22

这很直:

  • reverse.each 创建一个新数组然后循环每个元素

  • reverse_each 以相反的顺序循环(没有创建中间数组)

请参阅doc中的源代码:http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-reverse_each


Ale*_*øld 8

我肯定会说它与创建反向数组的时间有关!你只尝试过很小的数组(一个包含100个元素的数组仍然是一个小数组).如果你尝试使用更大的数组(例如10k元素),我想你会真正注意到它们的区别.