'Rails, is find_by().present? more performant than where().exists?

This question arose from me doing 2 types of performance tweaks:

  • changing a lot of my where().present? statements to where().exists?
  • changing a lot of my where().first to find_by()

Sitting at the intersection of this is situations where I had previously written .where().first.present? and I'm wondering what would be more performant to change it to: .find_by().present? or .where().exists?



Solution 1:[1]

  • Changing where().present? to where().exists?

where().present? or find_by().present? will always fetch the complete user record from the table:

SELECT * FROM xyz WHERE xyz.name = 'Deepesh'

whereas where().exists? or where().any? will run this query:

SELECT 1 FROM xyz WHERE xyz.name = 'Deepesh' LIMIT 1

So obviously exists? or any? would be better in terms of performance until you need that record you are checking to fetch some information or use it somewhere, for example:

user = User.find_by(name: 'Deepesh')
user.do_something if user.present?

so here you need to perform some action on that user if the record is present then using present? would be sensible.

Note: The time we would save using exists? would be the initialization of the ActiveRecord object, present? would initialize one, and exists will not. Read more here: https://stackoverflow.com/a/30192978/4207394

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1