We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Rob David • 7 years ago

I was just thinking about this the other day and wondering which one was faster. Thanks for breaking it down for us. I will be making these changes on all my Rails apps.

Prince • 7 years ago

Actually I don't think any one will ever check with present? like that:

Build.where(:created_at => 7.days.ago..1.day.ago).passed.present?

This will send a query without limit to the database and who knows how many records are there.

If I ever check like that I will be using:

Build.where(:created_at => 7.days.ago..1.day.ago).passed.first.present?

This will use the query with limit 1. Can you check the performance of the query with first also. Ofcourse it will load the columns also and will be slower than exists?, but it should be better than others.

But, exists is the best if you just want to check if that is in the DB and not use the result records for further code.

Luke Booth • 7 years ago

If you're not going to be using that ActiveRecord object, there's no reason to create it. Using `.first` will instantiate the AR object which is costly. If you just want to see if it exists in the database, use `.exists?` and leave AR out of the picture completely.

Will • 7 years ago

Very good post, great to see the numbers for each on production data. I'll be using exists? far more now.

Roman Gaufman • 7 years ago

From running a quick non comprehensive test, it seems there is zero difference between .present?, .any?, .exists? and .empty? with mongoid, if anyone is wondering :)

Prince • 3 years ago

Now with Rails 5.2, `any?` behaves similar to `exists?` when no block is given (also has the advantage of not querying again if the records are already loaded)