title: Slow belongs_to associations in Rails 3
body: <p>I have a model <code>Foo</code> with several belongs_to associations; I'll refer to them here as <code>Bar</code> and <code>Baz</code>. So the model would look like this:</p>
  
  <pre><code>class Foo
    belongs_to :bar
    belongs_to :baz
  
    def do_stuff_with_bar_and_baz
      bar.do_stuff(baz)
    end
  end
  </code></pre>
  
  <p>We noticed that <code>do_stuff_with_bar_and_baz</code> was unusually slow (~4 seconds), even though the underlying MySQL statements were very fast (~0.5ms). I benchmarked the <code>bar</code> and <code>baz</code> calls, and discovered that they took ~2.3s and ~221ms respectively... just to go through the Rails association code.</p>
  
  <p>I then put in the following methods:</p>
  
  <pre><code>class Foo
    belongs_to :bar
    belongs_to :baz
  
    def bar
      Bar.find(self.bar_id)
    end
  
    def baz
      Baz.find(self.baz_id)
    end
  
    def do_stuff_with_bar_and_baz
      bar.do_stuff(baz)
    end
  end
  </code></pre>
  
  <p>This bypasses the ActiveRecord association code and loads the associated records directly. With this code, the time to load the Bar and Baz in do_stuff_with_bar_and_baz dropped to 754ms and 5ms respectively.</p>
  
  <p>This is disheartening. The standard Rails associations appear to be horrendously inefficient, but I really don't want to have to replace <em>all</em> of them (that defeats a the purpose of a significant amount of ActiveRecord). </p>
  
  <p>So, I'm looking for alternatives:</p>
  
  <ul>
  <li>Is there something that I'm potentially doing wrong that's slowing things down? (The real code is obviously more complicated that this. However, the belongs_to is accurate; there's no additional options on the real code).</li>
  <li>Have other people encountered this?</li>
  <li>How have they dealt with it?</li>
  </ul>