Skip to content

Commit

Permalink
Avoid slowing down AR object initialization
Browse files Browse the repository at this point in the history
2d73f5a forces AR to enter the `define_attribute_methods` method whenever it
instantiate a record from the `init_with` entry point. This is a potential
performance hotspot, because `init_with` is called from all `find*` family
methods, and `define_attribute_methods` is slow because it tries to acquire
a lock on the mutex everytime it is entered.

By using [DCL](http://en.wikipedia.org/wiki/Double-checked_locking), we can
avoid grabbing the lock most of the time when the attribute methods are already
defined (the common case). This is made possible by the fact that reading an
instance variable is an atomic operation in Ruby.

Credit goes to Aaron Patterson for pointing me to DCL and filling me in on the
atomicity guarantees in Ruby.

[*Godfrey Chan*, *Aaron Patterson*]
  • Loading branch information
chancancode committed May 22, 2014
1 parent 2d73f5a commit 28d52c5
Showing 1 changed file with 1 addition and 0 deletions.
1 change: 1 addition & 0 deletions activerecord/lib/active_record/attribute_methods.rb
Expand Up @@ -66,6 +66,7 @@ def initialize_generated_modules # :nodoc:
# Generates all the attribute related methods for columns in the database
# accessors, mutators and query methods.
def define_attribute_methods # :nodoc:
return false if @attribute_methods_generated
# Use a mutex; we don't want two thread simultaneously trying to define
# attribute methods.
generated_attribute_methods.synchronize do
Expand Down

0 comments on commit 28d52c5

Please sign in to comment.