DEV Community

SakuraMilkTea
SakuraMilkTea

Posted on

.present? VS .any? VS .exists?

Image description

Something I have a difficult time wrapping my head around as a newbie is how actually super important it is to care about query speeds.
Different methods will have vastly different query speeds, and it's therefore to my advantage to understand how they actually work, in order to use the one that will do what I want while keep everything running smooth.

Here are three methods I've been using recently that kind of look the same, but run differently in the background and therefore have different uses!

  • .present?
[ "", " ", false, nil, [], {} ].any?(&:present?)
# => false
Enter fullscreen mode Exit fullscreen mode

This one tests for an object's general falsiness. As per the documentation, "An object is present if it’s not blank?. An object is blank if it’s false, empty, or a whitespace string."
Very important to point out that .present? initializes ActiveRecord for each record found(!). It effectively goes through the whole relevant database available.

  • .any?
person.pets.count # => 0
person.pets.any?  # => false
Enter fullscreen mode Exit fullscreen mode

This one will use a SQLCount to see if it's > 0, and therefore, although faster than .present?, still takes time and queries the database multiple times.

  • .exists?
Note.create(:title => 'Hello, world.', :body => 'Nothing more for now...')
Note.exists?(1) # => true
Enter fullscreen mode Exit fullscreen mode

This one, according to the documentation, "asserts the existence of a resource, returning true if the resource is found."
The beauty of .exists? is that it uses SQL LIMIT 1 to just check if there's at least one record, without loading them all or counting them all!
In a case where I just want to know if an object is there or not, this is without a doubt the best option.

And now to remember these three...

Let's do our best!

Top comments (0)