Empty? vs blank? vs any? – why you should not use any? to test if there’s anything in the array

I often work with junior programmers and somehow they tend to use syntax like this:

return unless array_data.any?
# or
do something if array_data.any?

And there's almost nothing wrong with it, as long as you don't work with huge arrays.

Here's a difference in speed between empty?, blank? and any? with different array sizes (worse scenario):

worse-scenario

Why any? is so slow with bigger arrays? Well, basically because it iterates through the whole the collection and checks if there's at least one non-false and non-nil element (when no block given). Of course it will stop with the first non-false value, but we were pessimistic and we assumed that there are no elements like that. Many developers assume that any? answers the: "is there anything in the array" question, when it really answers: "is there at least one non-false and non-nil element in the array". And this can make huge difference with bigger arrays.

Of course if we decide to have a true-like value in a random place of an array, things look a bit different:

randomMore or less it looks randomly, but you can see a general pattern - the more elements there are, the longer it can get.

Conclusion: Using any? to determine, if there's anything in the array can have a huge impact on your code performance if you work with bigger arrays. And even if you don't, having bad habits is not a good idea.

Categories: Ruby, Software

2 Comments

  1. Johannes Müller

    June 3, 2015 — 11:35

    Feels like this post is missing a conclusion … What about empty? and blank?

  2. Michel Pigassou

    June 3, 2015 — 19:55

    According to the code, #empty? just checks the length of the array (http://ruby-doc.org/core-2.2.0/Array.html#method-i-empty-3F).

    #blank? is a Rails method (active support actually) checking if it’s nil or empty.

Leave a Reply

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

*

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑