Tips to improve Rails code performance

Tram Ho

Use where instead of select

When performing a lot of calculations, the less data is loaded into memory the better, always use SQL queries instead of object methods.

For example:

The code will run faster if written like this:

 

Use pluck instead of map

If only a few values ​​are interested in each row, pluck should be used instead of map

For example:

Map will load all data into memory first, then perform id, pluck faster because it does not have to load data first.

Use ActiveRecord::Calculations#sum instead of Enumerable#sum

Normally when performing calculations sometimes we use Enumerable::sum to sum, this is a common mistake because ActiveRecord::Calculations gave us a way to calculate without loading a pile of data into the set. remember first. If you want to perform Rails calculations, ActiveRecord::Calculations is the best option to use.

Use ActiveRecord::Calculations#maximum instead of Enumerable#max

As explained above, we should use ActiveRecord::Calculations to improve the calculation

Use ActiveRecord::Calculations#minimum instead of Enumerable#min

Use Model.find_each instead of Model.all.each

A common mistake is to use ActiveRecord::Scoping::Named::ClassMethods#all + ActiveRecord::Result#each to iterate over a table of thousands of records.

The all method will load all data into memory first, which can lead to many memory problems. To be clear, the problem here is not the method all but the number of records it loads.

To process, we load records into each batch (default is 1000 records):

To customize the number of records:

You can specify the starting point of the batch, which is useful if there are multiple workers processing in the same queue, you can let one worker process records from id 1-5000, and the other worker handles records with id from 500 onwards.


Reference : https://www.fastruby.io/blog/performance/rails/writing-fast-rails.html

Share the news now

Source : Viblo