我几乎不使用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)