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 when 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 fields, 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.

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 methods 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, this code:

User.where(active: true).pluck(:name)

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

["Barny Gumble", "Bart Simpson", ...]

Try using pluck 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:

User.where(active: true).pluck(:id, :name)

[
[1, "Barny Gumble`"],
[2, "Bart Simpson"],
]

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 using pluck , your allocated memory and the database time are 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.

I recommend using select for models with large text fields or lots of fields that 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 this. 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.