Memoization
Memoization stores the result of a function call against the arguments it was given. When the function is called again with the same arguments, it returns the stored result instead of working it out again. It trades memory for speed, and it pays off when a function is slow and is called repeatedly with the same inputs.
A memoized function
Section titled “A memoized function”A Map makes a good cache, because its has() method says whether a key has been stored:
const cache = new Map();
function shippingCost(weightKg) { if (cache.has(weightKg)) { return cache.get(weightKg); } console.log(`Calculating for ${weightKg} kg`); const cost = weightKg <= 2 ? 3.5 : 3.5 + (weightKg - 2) * 1.25; cache.set(weightKg, cost); return cost;}
console.log(shippingCost(5));console.log(shippingCost(5));console.log(shippingCost(1));This prints:
Calculating for 5 kg7.257.25Calculating for 1 kg3.5The second call for 5 kg skips the calculation. The cost here is cheap to work out, so the example only shows the mechanism, but the same pattern saves real time on a slow calculation.
A reusable memoize()
Section titled “A reusable memoize()”Rather than building a cache into each function, a wrapper can add one to any function. It keeps the cache in a closure and turns the arguments into a string key:
function memoize(fn) { const cache = new Map(); return (...args) => { const key = JSON.stringify(args); if (!cache.has(key)) { cache.set(key, fn(...args)); } return cache.get(key); };}
let runs = 0;const countVowels = (text) => { runs += 1; return [...text].filter((ch) => 'aeiou'.includes(ch.toLowerCase())).length;};
const fastCountVowels = memoize(countVowels);
console.log(fastCountVowels('Wuthering Heights'));console.log(fastCountVowels('Wuthering Heights'));console.log(fastCountVowels('Dracula'));console.log(`countVowels ran ${runs} times`);This prints:
553countVowels ran 2 timesJSON.stringify() suits arguments that are numbers, strings and plain data. It cannot tell apart values that serialise the same way, such as undefined and null inside an array, and it loses functions, so a function taking those needs a key built another way.
Recursion
Section titled “Recursion”Memoization makes the biggest difference to recursive functions that solve the same smaller problem many times over. routes() counts the paths across a grid that move only right or down, and each call makes two more calls:
let calls = 0;function routes(rows, cols) { calls += 1; if (rows === 1 || cols === 1) return 1; return routes(rows - 1, cols) + routes(rows, cols - 1);}
console.log(routes(12, 12), `${calls} calls`);
const known = new Map();let memoCalls = 0;function fastRoutes(rows, cols) { memoCalls += 1; if (rows === 1 || cols === 1) return 1; const key = `${rows},${cols}`; if (!known.has(key)) { known.set(key, fastRoutes(rows - 1, cols) + fastRoutes(rows, cols - 1)); } return known.get(key);}
console.log(fastRoutes(12, 12), `${memoCalls} calls`);This prints:
705432 1410863 calls705432 243 callsBoth give the same answer, but the memoized version works out each grid size once, so it makes a few hundred calls instead of more than a million.
Pitfalls
Section titled “Pitfalls”Testing the cached value itself, as in if (cache[key]), treats a stored 0, empty string or false as missing, so those results are worked out again every time:
const cache = {};let runs = 0;
function stockLeft(item) { if (cache[item]) { return cache[item]; } runs += 1; cache[item] = item === 'pears' ? 0 : 10; return cache[item];}
stockLeft('pears');stockLeft('pears');stockLeft('pears');console.log(`stockLeft did the work ${runs} times`);This prints:
stockLeft did the work 3 timesChecking with cache.has(key) on a Map, or with key in cache on an object, avoids this.
Some other points to keep in mind:
- Memoize only pure functions, whose result depends on nothing but their arguments. A function that reads the clock, a random number or outside state would return stale results.
- The cache grows with every new set of arguments, and nothing empties it. For a long-running program, limit its size or clear it when the data behind it changes.
- A cached object is returned by reference, so a caller that changes it changes the cached copy for every later caller.
Steve Griffith covers this topic in his video What is Memoization?.