Improve Page Speed with Pagination in Rails

December 13, 2012 Link to post  Permalink

When you start a new web application, there’s likely to be very little data in your system. Hopefully, over time your users will find your application useful and add data. At some point, loading index pages will become slower and slower due to this extra data. It’s time for pagination.

The math is pretty simple. If you have 500 items on a page, and you can reduce that to, for instance, 50 items, the time to display those items is likely to be 10 times faster. Now, there are some constants here with header/footer/sidebar pieces that are the same no matter how many items you have, but the difference between 500 and 50 items will be very obvious to your users.

There are two different paginates available for Rails. I’ve been using will_paginate for several years, but there is a new kid on the block called kaminari. Which one you use may just be a matter of taste. Try one and switch if you don’t like it!

For the published posts for this blog, I ran some tests. My index page post retrieval code looks like this:

@posts = Post.published.order("published_at desc")

On a test system, my blog page with all posts renders in about 600ms.

When I add pagination to the system and repeat the test with a page size of 10

@posts = Post.published.order("published_at desc").paginate(:page => params[:page], :per_page => 10)

Now the page renders in under 100ms.

Make sure to keep track of your new applications and add pagination to keep page performance up as the amount of data grows.