Faster Rails: How to Check if a Record Exists

Ruby and Rails are slow — this argument is often used to downplay the worth of the language and the framework. This statement in itself is not false. Generally speaking, Ruby is slower than its direct competitors such as Node.js and Python. Yet, many businesses from small startups to platforms with millions of users use it as the backbone of their operations. How can we explain these contradictions?

Imported from Disqus

Prince4 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 Prince4 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.

Avatar

Roman Gaufman4 years ago • edited

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 :slight_smile:

Prince21 days 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)