I hardly use reverse_each
method, instead I call upon reverse.each
when I need to traverse an array backwards. So I just did some benchmarking and apparently reverse_each
is significantly faster than reverse.each
.
- Is this because there is an element of time associated with creating a reverse array before iterating through it when using
reverse.each
?
However in my example (below) of 10 million iterations TIME(reverse) + TIME(each) - TIME(reverse.each) ~ 1.2 seconds
for an array of size 4. And this time difference more or less stays stable irrespective of the size of array. I have tested it for upto 100 elements.
- What accounts for this one second difference?
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