Memoization

Memoization is the simplest performance tool there is: compute a value once, hand back the same answer every time after. Ruby's idiom for it — @value ||= compute — is so short that it hides three real bugs, and fixing them by hand produces exactly the kind of boilerplate a library should own. This guide covers why we use memo_wise, how to use it, and — the part that matters more than the syntax — when memoizing is the wrong call.

1. Why memo_wise Over the ||= Idiom

The ||= idiom re-runs the method whenever the cached value is falsy. A lookup that legitimately returns nil or false — "does this user have a subscription?" — is never memoized at all; it just runs on every call while looking cached. The fix is defined?(@x) ? @x : (@x = …), which is correct and unreadable. Add a method argument and you are now hand-maintaining a hash keyed by the arguments. Add a second thread and you are reasoning about races.

Before
def subscription
  # nil is never cached: this runs every call
  @subscription ||= Subscription.find_by(user: user)
end

def price_for(plan)
  @price_for ||= {}
  return @price_for[plan] if @price_for.key?(plan)

  @price_for[plan] = PricingEngine.quote(plan, user)
end
After
prepend MemoWise

memo_wise def subscription
  Subscription.find_by(user: user)
end

memo_wise def price_for(plan)
  PricingEngine.quote(plan, user)
end

memo_wise gets all of that right — nil and false are memoized, arguments are keyed automatically, class and module methods work, and memoized methods are inherited — with documented thread-safety guarantees (before a value is memoized, concurrent callers may each run the method but exactly one result is stored; after, every caller gets that result) and reads that benchmark faster than every other memoization gem. It also gives you first-class reset and preset helpers, which the ||= idiom has no answer for at all.

2. Installation

Add the gem to your Gemfile and run bundle install. There is no generator and nothing to configure.

# Gemfile
gem "memo_wise", "~> 1.13"

3. Usage

prepend MemoWise in the class, then mark methods with memo_wise. It accepts a method name or the def itself (since def returns the method's name as a symbol), so the decorator form reads naturally. Memoized methods keep their visibility, so private still applies:

# app/models/invoice.rb
class Invoice < ApplicationRecord
  prepend MemoWise

  # No arguments: computed once per invoice instance.
  memo_wise def total
    line_items.sum { |item| item.quantity * item.unit_price }
  end

  # With arguments: computed once per distinct (currency) value.
  memo_wise def total_in(currency)
    CurrencyConverter.convert(total, from: "USD", to: currency)
  end

  private

  memo_wise def tax_rate
    TaxTable.rate_for(billing_address.region)
  end
end

Class methods memoize the same way with the self: form. This is the natural home for data that is genuinely constant for the life of the process, such as a parsed configuration file:

class FeatureFlags
  prepend MemoWise

  def self.definitions
    YAML.load_file(Rails.root.join("config/feature_flags.yml"))
  end
  memo_wise self: :definitions
end
Blocks Can't Be Memoized

A method that takes a block — explicit &block or an implicit yield — cannot be memoized, because the block is part of the input and has no identity to key on. Restructure so the memoized method takes plain values.

4. Resetting and Presetting

A memoized value is a snapshot, and sometimes the world it was taken from changes. reset_memo_wise forgets memoized results — for one method, for one method with a particular argument, or for everything on the object — and preset_memo_wise stores a value without running the method at all:

invoice.reset_memo_wise(:total)              # forget total
invoice.reset_memo_wise(:total_in, "EUR")    # forget one argument's result
invoice.reset_memo_wise                      # forget everything on this object

invoice.preset_memo_wise(:total) { 0 }       # store 0 without computing

FeatureFlags.reset_memo_wise                 # class methods reset the same way

Two places this matters:

  • Objects that outlive the data they memoized. A request-scoped object (a component, an interaction, a presenter) is thrown away before anything can go stale, so it rarely needs a reset. A model that memoizes a derived value and then has a setter called does — reset in the setter, or don't memoize the derived value.
  • Tests that share an instance. Rails view helpers are modules that rspec-rails tests through a single shared helper object, so a memoized helper method keeps its result from one example to the next. Reset between examples:
# spec/helpers/pricing_helper_spec.rb
RSpec.describe PricingHelper, type: :helper do
  after { helper.reset_memo_wise }
end

5. When to Memoize — and When Not To

memo_wise makes memoizing so easy that the discipline has to come from you. The test is simple: the method is pure, it is expensive or called repeatedly, and the answer cannot change during the object's lifetime. Miss any one of those and memoization is a bug waiting for the right input.

SituationMemoize?Why
A pure, deterministic method that is expensive and read repeatedly during one object's lifetime Yes

The textbook case: a parsed config, a computed total, a resolved association.

A method that takes arguments and is called with the same few values over and over Yes

memo_wise keys the result by argument, so each distinct input is computed once.

Anything that reads request-varying state — the current user, `Time.current`, `params` No

The value is only right for one moment; a long-lived object will serve it forever.

A method with side effects (writes, emails, logging) No

Memoizing it means the side effect happens once and then silently never again.

A cheap call — an attribute reader, a small arithmetic expression No

The hash lookup costs about as much as the work it saves, and you have added a stale-state hazard for nothing.

A method called with many distinct arguments on a long-lived object No

Every argument set is retained; this is a memory leak with a decorator on it.

The object's lifetime is the variable people forget. A ViewComponent or an interaction lives for one request, so memoizing freely inside one is safe: nothing it caches can outlive the request that produced it. A class method, a constant, or a singleton lives for the whole process, so only genuinely immutable data belongs there — and a deploy is the only reset it will ever get.

6. Pitfalls

Memoizing across state changes. memowise does not watch your instance variables. Set invoice.currency = "EUR" after `totalin` has been memoized and the old answer stays. Either reset in the setter or keep memoized methods on objects that don't change after construction.

Memory retention. Results for methods with arguments are kept per distinct argument set, and nothing evicts them. On a request-scoped object that is a rounding error; on a long-lived one it is unbounded growth. If the argument space is large — record ids, timestamps, user input — reach for Rails.cache with an expiry instead.

dup shares the memo store. Ruby's dup copies instance variables shallowly, and memo_wise keeps its results in one of them, so a copy and its original read and reset the same cache. Marshalling round-trips memoized state intact, which is usually what you want; sharing a store between two live objects usually is not. Reset the copy, or don't memoize on objects you copy.

Memoize the Expensive Thing, Not the Whole Method

When a method mixes a slow lookup with cheap, state-dependent logic, split it: memoize the lookup in a private method and leave the logic unmemoized. The cache then stays correct no matter how the object's state changes.

Success!

You have a memoization tool that handles the edge cases for you and a rule for when to reach for it. Before you move on:

Made with by Profoundry .
Copyright © 2023-2026 Profoundry LLC.
All rights reserved.