Only memoize pure functions, bound the cache, and watch out for reference equality on object arguments.
Memoization without memory leaks
Only pure functions
If
f(x)has side effects or depends on external state, memoization returns stale data.Bound the cache
An unbounded memo on a long-running server is a memory leak. Use an LRU map.
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.Invalidations
If the underlying data changes (e.g., user profile updated), the memo must be invalidated manually.