Read more

Be careful with "memoize"

Tobias Kraze
November 07, 2011Software engineer at makandra GmbH

ActiveSupport's memoize has a dangerous feature you might not know about.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Assume you have

class DeepThought
  extend ActiveSupport::Memoizable

  def life_universe_and_everything
     # some lengthy calculation returning 42
  end
  memoize :life_universe_and_everything
end

Then #life_universe_and_everything will of course cache the result after calculating it once. However, you can trigger a recalculation by calling #life_universe_and_everything(true).

If, however, your method looks like

def life_universe(and_everything = false)
  ...
end
memoize :life_universe

a call to #life_universe(true) will actually trigger a reload and not pass the parameter at all.

To clarify: This not only disables the memoization, but will also return wrong results!

The best solution is to use the Memoizer gem instead.

Posted by Tobias Kraze to makandra dev (2011-11-07 16:10)