18

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

2 Answers 2

26

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

Sign up to request clarification or add additional context in comments.

1 Comment

It might be worth pointing out that this is only the case for Arrays, other Enumerables, including Hash, do create an intermediate Array for #reverse_each (see source), so it doesn't save any time for those.
9

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.

1 Comment

same answer, even faster :) +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.