This site is dedicated to further knowledge about creating Ruby on Rails applications professionaly. We discuss Ruby on Rails features from a performance angle, discuss Ruby on Rails performance analysis methods, provide information on Ruby on Rails scaling and benchmark Ruby on Rails performance for each release. We discuss best practices for selecting Ruby on Rails session containers, fragment and page caching and optimizing database queries.

Faster Pagination

Posted 03 Nov 2005

Rails version 0.14 and upward contain a massive performance improvement for pagination. Most of it is free and any app will benefit from it without even knowing.

However, there's also a little api addition to the pagination helper module, which can be used to speed up your paginated pages even more, if necessary.

We're talking about pagination_links_each. It takes the same parameters as pagination_links but instead of calling link_to to create the html code for each link, it yields the page number to a block. It is the block's responsibility to create the html code for the link.

So for example, you could write

pagination_links_each(pages, :window_size => 4) do |n|
    "<a href='?page=#{n}'>#{n}</a>"
end

instead of

pagination_links(pages, :window_size => 4)

The first version is faster than the second one, because it avoids creating lots of intermediate data structures to generate the html code. Additionally, the created html is shorter and less data gets transmitted over the wire. And the code will work for any page embedding it.

The speedup obtained will of course depend on your app. Here's some data for paginated pages of my application, showing speedups ranging from 11 to 26%. Quite an improvement for adding one line of code!

Posted in performance | Tags pagination

Comments

blog comments powered by Disqus