Performance Your Ruby on Rails App

Tram Ho

When working with any language, in addition to writing the code that runs properly with the logic of the problem, how to write code so fast program performance is equally important. I recently did the optimization for a project and found some problems and solutions for project performance.


As our applications grow larger, they certainly tend to contain more data and require increasingly complex queries. So query optimization issues need to be optimized to improve the program.

Indexing: Why and When

index the database as an index on the back of a book; Instead of reading the entire book, you can scan an alphabetical index to know the location of what you’re looking for, and then skip to that page. In general, any column you usually use to find the result (WHERE) or sort (ORDER) can be an index. Foreign keys are often indexed to improve performance. You can check your logs (or the Rails server output in the control panel) to check which queries are slow.

ActiveRecord automatically indexes – every input index has its own id, which acts as the primary key. Primary keys are indexed by default; You may notice that finding something by id is faster. In reality, however, we need to search more fields in the table, which need to be indexed for faster searching.
We use this command to create an index in rails:

rails g migration add_index_to_name_column_on_person We have the following index:

Now we query the Person table with 30,000 records. Query time has decreased quite a lot.

Partial Indexing

Partial Indexing allows us to index by the condition of the column

This speeds things up, saves space and doesn’t waste memory. If Partial Indexing suits your needs, you should absolutely use it instead of the full index.


To get two fields in a table into an array, I did the following:

the following results:

[[2136, “name”], [2137, “name”], [2138, “name”], [2139, “name”], [2140, “name”]] However, after learning about pluck and Application time has greatly reduced, People can refer here

Fix N +1

After the query, the log query above will be as follows:

The above code executed a lot of queries, one to retrieve all users, and N queries to execute based on the number of users. That’s the problem with N + 1 and to fix we use Eager loading. After using Eager loading we have solved the problem of n + 1, not only using Eager loading can solve n + 1, such as cache query, everyone when the code is up, pay attention to the log when we write the code. .N + 1 is also a part of the program performance degradation.

log query:

After using Eager loading only creates 2 queries, one command to retrieve all users, and the other to retrieve all products belonging to that user.

Hopefully, what I share can help you improve the performance of your application. Happy coding!

Share the news now

Source : Viblo