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
.
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.
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
It's pretty straight forward:
reverse.each
creates a new array then loops each element
reverse_each
loops in reverse order (no intermediate array created)
See source code in doc: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-reverse_each
I would definitely say it has to do with the time associating with creating the reverse array! You've only tried really small arrays (an array with 100 elements is still a small array). If you try with bigger arrays (for instance 10k elements), I think you will really notice the difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With