Sikau

Advanced JavaScript · Day 5 · about 30 min

Project: Speed up with memoize

Remember answers so you never compute twice.

Never work twice

Some functions are slow but always give the same answer for the same input. Memoizing keeps a note of every answer, so the second time you ask, it answers instantly. You'll build it with closures and higher-order functions.

The idea

function slowSquare(n) {
  for (let i = 0; i < 1e7; i++) {}
  return n * n;
}

const cache = new Map();
function fastSquare(n) {
  if (cache.has(n)) return cache.get(n);
  const result = slowSquare(n);
  cache.set(n, result);
  return result;
}

let t = Date.now();
fastSquare(9);
console.log("first:", Date.now() - t, "ms");
t = Date.now();
fastSquare(9);
console.log("second:", Date.now() - t, "ms");

The rest of this lesson

  • How memoize worksexplain
  • When memoizing pays offexplain
  • Counting real callspredict
  • Memoize or not?match
  • Build memoizechallenge
  • Badge quizquiz
  • Unit 1 complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript