Skip to content

How to memoize well

Only memoize pure functions, bound the cache, and watch out for reference equality on object arguments.

Memoization without memory leaks

  1. Only pure functions

    If f(x) has side effects or depends on external state, memoization returns stale data.

  2. Bound the cache

    An unbounded memo on a long-running server is a memory leak. Use an LRU map.

  3. Reference equality

    memoize(f)([1,2]) will not hit the cache for [1,2] because arrays are compared by reference. Use a custom key resolver.

  4. Invalidations

    If the underlying data changes (e.g., user profile updated), the memo must be invalidated manually.