Joel
Joel

Reputation: 4603

Which ActiveRecord query is faster?

These three queries return the same result. How can i find out which one is faster?

IssueStatus.where 'issue_statuses.name != ?', IssueStatus::CLOSED

IssueStatus.where({name: ["Open", "Ice Box", "Submitted for merge", "In Progress"]})

IssueStatus.where.not(name: "Closed")

Upvotes: 2

Views: 274

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176562

There is no single answer: it depends on whether you have indexes on the field, and the number of records. You can append .explain at the end of the query to get the result of the Query Plan for the query.

puts IssueStatus.where.not(name: "Closed").explain

That will help you to understand, at database level, which one is the faster. From a database POV, the first and the third query are actually the same.

The third chains one more methods call, therefore it involves some additional object allocation at Ruby level (without mentioning that "Closed" causes the creation of a new string, whereas using IssueStatus::CLOSED does not).

At first glance, I would probably suggest to use the first version. But as I said, the query plan will give you more details about the query execution.

Upvotes: 3

Related Questions