james
james

Reputation: 4049

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

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

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?

Upvotes: 2

Views: 940

Answers (1)

Deepesh
Deepesh

Reputation: 6398

  • 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

Upvotes: 3

Related Questions