3 ways to optimize Rails views performance

Tram Ho


Hi everyone, hi guys!

You’ve heard “Do activity first, optimize later” =)) and nowadays we usually do it somewhere, but when there is a problem, going back to processing it will take time. And doing it well in the first place can be difficult, but it will give us more time for other matters.

In this article, we’ll take a look at some simple and effective performance optimization techniques you can use right from the start of coding.

So let’s get started (go)

First we create a Rails app using mysql:

Then create the model, in this article I use 2 tables:

  • Person (has many addresses)
    • name: string
    • votes_count: integer
  • Profile (belongs to Person)
    • person_id: integer
    • address: string

To create these two models, we run the command:

Then run the following command to create the database and table:

The schema file looks like this:

Model file:

Add validatons for the model:

Next we create data to display, you can use the gem Faker to fake name, address … more easily.

Once the seeds.rb file is created, it should look like this:

Next run the command: rails db:seed

And now we will create a controller called PersonController with the index action with the command:

And add logic to remove all persons:

File people.html.erb :

File _person.html.erb

Try to see the site’s performance.

Oh no, a huge amount to load. That with only 1 request, try to imagine we have 10, 100, 1000 requests at the same time, how will it be? Sitting more than 1 minute does not load the web page, and that you are making your customers say goodbye to your website and not see you again. So what do you have to do to retain your customers? Of course it has to be improved. So how to improve? Please join me in each part.

1. Database queries

The first step in building an efficient application is to maximize resource usage. Most Rails applications take data from the database to render the views. So we need to optimize the calls to the database.

Looking above you can see we have n + 1 query.

1.1. N + 1 QUERIES

This error is quite common when we have a query that gets the data of the child table through the parent table. Look at the render view code in the _person.html.erb file we just used:

Basically, it queries the database to get the profile of the person and render it for each person. That’s N Queries (N is the number of people) plus 1 main query is SELECT people .* FROM people => Called N + 1 queris.

To get around this problem, rails supports several ways: Preload , Eagerload , Includes and Joins

Try changing the controller code a bit:

Track log:

As you can see the load time has decreased from 3834ms to 954ms, pretty much right ?. However, this number is still quite large, so let me see the next ways.

1.2. Only load the used parts.

As the code above, our homepage should look like this:

You can see we just need the address, don’t need anything else. But in the _person.html.erb file we load the profile object as well. Change the hill a bit.

Track results:

Not very significant, right: v

1.3. Use paging

One way to improve the performane is to use pagination, which is to show only the right amount of data, then see more by clicking see more. You can learn about pagination gems like: pagy , will_paginate , kaminari

Depending on the requirements of the site you can use pagination like clicking “next page / next page” or using “Infinite Scrolling” to provide better user experience.

2. Avoid reloading HTML

In a Rails application, the HTML view takes a long time to render. Luckily, there are several methods that can help us fix this.

2.1 Using Turbolinks

Turbolink is added in the rails app, when we run the rails new command. Turbolink is a Javascript library that works everywhere (even without Rails, as on static pages) and it can degrade quality in browsers that don’t support it. So you can consider when using this library.

It converts every link into an AJAX request and replaces the entire content of the page through JS. This significantly improves performance as it doesn’t reload CSS, JS, and images.

However, when customizing JS you will be more cautious when writing “Turbolinks safe JS”. Read more here

2.2. Using AJAX

Similar to Turbolinks, we can also convert some links and buttons into AJAX requests. The difference here is that we can control what HTML is replaced instead of replacing the entire content like Turbolinks does.

3. Caching

Most of the load time is used to render the view. This includes loading all CSS, JS and images, rendering HTML from erb files, and more.

Another way to partially reduce load times is to determine if the app’s rendering will stay static for a period of time or until an event occurs.

3.1 Caching views

As above example to load 1000 records, we take ~ 2000ms

One gem that supports this caching view is Dalli

3.2 Caching database queries

Another way you can improve speed is by using the cache, which saves the data in the cache.

You can learn more about redis and the gems used in rails.

3.3. Database indexes

You can also use the index in sql for speed optimization. However, you should also consider when typing indexes for fields in the database, but not everything should be indexed =))


In this article we have explored how to improve the views performance of Rails app in a variety of ways. You can see which one is suitable for your application to apply. And if there is any other way, hope you will share it in the comment section of the article. Thanks very much.


Share the news now

Source : Viblo