[Ruby] Dumb ActiveRecord question

Eric Hodel drbrain at segment7.net
Fri Jan 5 17:44:43 PST 2007


On Jan 5, 2007, at 14:06, Alex Vollmer wrote:

> Get yer rotten veggies ready for this one...
>
> I have a bunch of lookup data in a couple of tables that gets  
> referenced
> over and over and over. When I include these lookup tables in a
> has_manyassociation with an
> :include declaration, ActiveRecord creates some LEFT OUTER JOIN SQL  
> that
> performs a sequential table scan.
>
> So insted of eagerly loading the objects through associations I  
> thought I
> would hand-roll a class-level method to capture find_by_id queries  
> and cache
> them in a hash defined in a class constant. Unfortunately it looks  
> like each
> time I run the request the cache is brand-new. Each table is less  
> than 100
> rows so holding these records in memory shouldn't have a big effect.
>
> The class looks like this:
>
> class Property < ActiveRecord::Base
>
>   self::ID_CACHE = {}
>
>   def self.find_by_id(id)
>     self::ID_CACHE[id] ||= super
>   end
> end

This'll work great until you get about ~1-200k objects.

$ ruby
puts 200_000 *
(4 + # VALUE to hold id
  4 + # VALUE to hold ActiveRecord object
  20) # Ruby object (minimum)
5600000

5.6M per process just to hold the AR object without any of the  
properties.  Adding the properties, you'll see far more than that,  
especially once the associations get loaded.

I suggest using the CachedModel gem instead.

-- 
Eric Hodel - drbrain at segment7.net - http://blog.segment7.net

I LIT YOUR GEM ON FIRE!



More information about the Ruby mailing list