View The Space is Hiring

Tuesday, December 10, 2013

Optimize Your Rails Fragment Cache By Lazily Loading your Objects

I was looking into the performance of our my portfolio page the other day which was supposedly cached.  Here's what I noticed within the controller.

And here was our view:

This being a page that show properties and spaces, we are attempting to cache the entire page based on some keys that get updated whenever any of the spaces or properties within the user's portfolio is updated.  But here's the problem, our queries are doing some eager loading from the database.  Even though we were fragment caching the entire page, each cached hit was still hitting the database, creating a bunch of active record objects and then never actually using them. Even on a cached hit, this is what I saw in the logs:

To fix this, we moved all of the query logic out of the controller show method and into a our query object where it is safely memoized

Now instead of accessing instance variables created within the controller show method, our view accesses helper methods lazily from within the cache fragment.

Our cached my portfolio page no longer needlessly loads dozens of active record objects.

No comments:

Post a Comment