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

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

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

然而,在我的示例(下面)中,1000万次迭代TIME(reverse) + TIME(each) - TIME(reverse.each) ~ 1.2 seconds对于大小为4的数组。并且这个时间差或多或少保持稳定,而不管大小如何数组。 我已经测试了多达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 

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

这很直:

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

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

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