Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Array.reverse_each is faster than Array.reverse.each

Tags:

arrays

ruby

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
like image 887
saihgala Avatar asked Oct 12 '12 12:10

saihgala


2 Answers

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

like image 124
apneadiving Avatar answered Oct 03 '22 19:10

apneadiving


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.

like image 30
Aleksander Blomskøld Avatar answered Oct 03 '22 18:10

Aleksander Blomskøld