In this conclusion to a six-part article series on optimizing the performance of a Ruby on Rails program, you'll learn about the most common performance problems you might encounter in Rails, and how to avoid them. This article is excerpted from chapter 13 of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Common Performance Problems in Rails (Page 1 of 2 )
Common Performance Problems in Rails
The performance of any web application can be severely crippled by small issues in the source code, and a Rails application is no different. Here, we’ll look at some of the most common performance problems in Rails applications and how to avoid them.
Rendering a page to a user should probably be the fastest and best optimized thing in a web application. Therefore, all really expensive calculations should be made at some other point. One example of this is textilizing content. In Chapter 3, we used the textilizemethod to transform the book blurb stored in Textile format to HTML. However, this formatting can just as well be done whenever the blurb is changed; that is, when the book is saved.
Let’s add a field for the blurb in HTML format to the database:
Now, whenever a book is saved, its blurb is also transformed to HTML.
We should find all thetextilizecalls in the application and replace them withblurb_html. For example, inapp/views/admin/book/show.rhtml, replace this line:
<dd><%= textilize @book.blurb %></dd>
with this one:
<dd><%= @book.blurb_html %></dd>
The result is one less expensive calculation to do in the page-rendering phase.
Caution Althoughtextilizeis a cool quick-and-dirty helper, as a rule of thumb, it should never be used in a production setting.
Another thing that can slow down rendering is building the URLs in link_to and form helpers. If your profiling shows that a url_for call is taking a lot of time, you might consider replacing the helper with a handwritten HTML tag. So, for example <%= link_to "Home", home_url %> would be replaced by <a href="/">Home</a>. However, remember to measure and profile. It serves no purpose to optimize these helpers unless you see that they are guilty of slowing down your application.