ActiveRecord: Speed up your SQL queries by reducing loaded data and prevent Model instantiation

At PhraseApp we provide weekly Brownbag sessions get new developers on board and share knowledge across the team. Last week I held a Brownbag session about how to improve and debug ActiveRecord generated SQL queries. This blog post series presents the basics of working with Rails and ActiveRecord to write a more performant code.

Today I want to share some knowledge about improving the performance of ActiveRecord queries by selecting only the needed data and reduce the number of instantiated objects. There are many cases in your Rails application where you only need a small subset of data and not the whole record. For example, if you want to render a user select box where you only need the “id” and “name” field you can use something similar to the following code:

 

But if we take a closer look here it is obvious that we instantiate an object for every user found on this account and also fetch all fields of the user table from the database. For a small amount of found records, this is not a big deal but imagine an account having thousands of users.

ActiveRecord provides methods that solve this issue without writing crazy custom SQL queries.

Load only the Data you need!

If you are using Model.find, Model.where, etc. Active Record will generate SQL like SELECT models.* WHERE (condition). Most of the time this is tolerable but if you select a lot of records and don’t need all fields this will load a lot of unneeded data into the memory.
In the end, this results in a longer DB time and, moreover, wastes a lot of memory. You can use the pluck and select method to increase the overall performance.

 

pluck

The pluck method allows you to select only a subset of requested fields and stores them in an array.

For example:

 

will return all names of active users in an array like:

 

Try usingpluck to select multiple fields. The returned Data will be structured in a two-dimensional array.
Let’s assume you want also select ids of your active user:

 

In my opinion a typical use case for pluck is the selection of data for select boxes, using ids as sub-selects in a where clause. Typically you should think aboutpluck in every case you see something like collection.map { |record| record.field }.

By usingpluck your allocated memory and the database time is reduced. Often, you can remove time constructs like .map{ ... } and make your code more compact.

 

select

The select Method is another way to limit the fields selected from your database. The main difference to pluck is that an ActiveRecord model object is created, instead of returning an array of the selected fields. This allows you to call methods on this model.

Be careful: if you try to access a field that was not selected it will raise an ActiveModel::MissingAttributeError.

I recommend to use select for model with large text fields or lots of fields you don’t need to load. A typical use case at PhraseApp is our translations table. When we only want to verify a batch of translations we don’t need to load the whole content.

 

Benchmark

Finally, a simple benchmark approves tis. This benchmark compares the time needed to load 10 000 ids of a record into an array using (pluck,select and loading full records). As expected the pluck solution is the fastest followed by select (10 times slower thanpluck). The solution without selecting only specific fields takes the last place being 20 times slower thanpluck.

Further Reading

If you are interested in the ActiveRecord topic, also make sure to check out our Pitfalls In The Validation For Uniqueness Using Rails ActiveRecord blog post!

Comments