Ruby Array#each vs Enumerable#any?

So I had a little snippet of code that a coworker of mine mentioned I could replace:

collection_thingy.each do |val|
  return if val.prop == :particular_thing


return if collection_thingy.any? { |val| val.prop == :particular_thing }

And that got me thinking about which was faster. So I did some quick benchmarking. Results and code are embedded below.

Clearly Array#each is faster than using the equivalent Enumerable#any?, and by 13-28% depending on the array size. That seems like a lot. I’m not enitrely sure why it’s that much faster but it’s interesting. Still, for most cases there is a negligble difference (especially in a Rails app), just be aware of the difference if you’re traversing giant arrays (on 1Billion elements its as much as 14 second difference in my environment).

Here are some graphs showing the speedup more visually (imgur album of graphs):
1M Elements
10M Elements
100M Elements
1B Elements

All that being said, if performance isn’t an issue in the particular codeblock Enumerable#any? is more readable. Feel free to post your own results as actual runtimes will vary from environment to environment.

2 Responses to Ruby Array#each vs Enumerable#any?

  1. This post is on 18 spot in google’s search results, if you want more traffic, you should
    build more backlinks to your posts, there is one trick to get free,
    hidden backlinks from authority forums, search on youtube; how to get
    hidden backlinks from forums

Leave a Reply to Daniel Cancel reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>