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!