JavaScript · Performance · Senior · Best Practice
When is memoization a good performance strategy in JS, and when does it hurt?
Short Interview Answer
Memoize pure expensive functions with stable inputs; avoid memoizing cheap functions or unbounded caches that leak memory.
Detailed Explanation
Memoization trades memory for CPU. Good: parsing, complex derived data with repeated identical inputs. Bad: functions with unique inputs each call (cache thrash), impure functions, or caches without eviction. In UI frameworks, over-memoization adds comparison overhead and complexity. Profile first. Prefer algorithmic improvements over micro-memo. Use WeakMap when keys are objects that should not retain memory.
Example
function memoize(fn) {
const cache = new Map();
return (key) => {
if (cache.has(key)) return cache.get(key);
const v = fn(key);
cache.set(key, v);
return v;
};
}Interview Tip
Say 'measure first' — avoids premature optimization stigma.
Common Mistake
Unbounded memo caches on user-generated keys (memory leak).