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

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.

Tags:

Arrays

Ruby