DEV Community

Scott McKeon
Scott McKeon

Posted on

Performance enhancement, Rails style: Eager Loading and Caching

When we use a basic-written Rails app to paint a page, it draws from each associated table multiple times (this is known as the "n+1 problem"). This causes the page to load relatively slowly, and can become a problem for complex or large query requests.

For example, when painting comments, it will go to the user table for the main user, then the photo table for each photo, then the comment table for every comment, then the user table for every comment (to find the author).

You can use the gem bullet to find spots in your application that have the n+1 problem, and then use "eager loading" to grab all the information that you need in one shot, instead of making multiple, sequential requests to the database.

To do this, use the includes() method, as below:

<% @user.feeds.includes(:owner, { :comments => [:author] }).each %>
Enter fullscreen mode Exit fullscreen mode

Another trick to page performance is to use "caching." This technique essentially lets the browser pre-load everything it expects you to want to see, and then render it somewhat instantaneously.
Check out the Rails Guide for a great breakdown of how to do it.

Top comments (0)