Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
ActiveRecord Performance | 165

ActiveRecord Performance


Object-relational mapping systems provide such a high-level environment for work-
ing with data that it is easy to forget about efficiency until it becomes a problem.
Here are some common problems and solutions for ActiveRecord development.


Diving into SQL


When faced with a problem that doesn’t map neatly to the given abstractions, most
programmers have an instinct to jump down a level. When using ActiveRecord, this
means using raw SQL.


For security as well as performance, it is important to understand the SQL that is
being generated from the commands you issue. ActiveRecord provides a useful
abstraction, but if you are not careful, it will bite you.


The simplest way to drop into raw SQL is to useActiveRecord::Base.find_by_sql.
This is a very flexible method that returns the same results asfind(:all, ...), but
allows you to specify custom SQL. It will even sanitize an array for you:


Person.find_by_sql ["SELECT * FROM people WHERE name LIKE ?", "#{name}%"]

Figure 6-5. Performance comparison between the control and two optimized versions


45.0

44.5

44.0

43.5

43.0

42.5
Before optimization Location optimization Refactoring

Response time per 100 requests (s)
Free download pdf