title: ActiveRecord Slow Object Instantiation
body: <p>I maintain a website of events taking place in my city.</p>
  
  <p>My website homepage is a 5-days calendar with all the events taking place from today to 4 days in the future.</p>
  
  <p>I have done quite a good job with my "ActiveRecord" code as I have around <strong>~120ms spent in MySQL</strong> (double checked with RackMiniProfiler) to load ~200-300 events.</p>
  
  <p>However my response time is very slow (1.5s - 2s).</p>
  
  <p><strong>Most time is spent in instantiation of AR's objects from my queries</strong></p>
  
  <p>Using ObjectSpace, I see that <strong>~6k AR::Base objects are instantiated</strong> for +300 events that are displayed. </p>
  
  <p>The reason why there are so many objects is that my <strong>Event</strong> model has many associated models (e.g. venue, occurrences, categories, etc...), all of which contain bits of information I need to show.</p>
  
  <p>As expected, profiling proved ActiveRecord's object instantiation as the most consuming task during the request.</p>
  
  <p>I am not experienced enough in neither ActiveRecord nor its performance.</p>
  
  <p>Is such speed expected or should my objects be instantiated much faster? </p>
  
  <p>Should I move away from AR and use <strong>simple ruby hashes</strong>?</p>
  
  <p>Is this the <strong>Rails standard</strong> when my data model is too complex?</p>
  
  <p><strong>========= UPDATE 1 =========</strong></p>
  
  <p>This <a href="http://pastebin.com/3VkfGS1Y" rel="nofollow noreferrer">pastebin</a> contains the service class I use to load the events for a single day in the calendar.
  I hope it's understandable, I did not have time to properly document it since it's still a work in progress to improve performance.</p>
  
  <p><strong>========= UPDATE 2 =========</strong></p>
  
  <p>Loading all these objects has another drawback: it causes <strong>GC runs</strong> while the page is being rendered, adding ~100ms after every <em>n</em> events are rendered, which becomes a total overhead of ~500ms.</p>
  
  <p>To give you an idea of how much data I'm loading (sadly 99% of it is needed), <strong>if I dump to JSON I get a 47K file</strong>.</p>
  
  <p><strong>========= UPDATE 3 =========</strong></p>
  
  <p>As mentioned by @TheSuper, even though it does not improve AR's performance, fragment caching is indeed my friend as I'm rendering quite the amount of data while under GC runs. Applying <strong>fragment caching</strong> yielded a 1-1.2s improvement, which is HUGE.</p>
  
  <p>However I still cannot overcome the 600ms wall of AR.
  A possible improvement are <em>"selective includes"</em> discussed in <a href="https://stackoverflow.com/questions/12400860/activerecord-includes-specify-included-columns">this answer</a>, for the few cases where I need a small portion of the attributes of an included model, but this is ugly and inflexible.</p>