25 min·advanced

Lesson 4

Memoization & performance

Build a practical mental model for memoization & performance and use it in working JavaScript.

By the end, you will be able to…

  • Explain memoization & performance in your own words
  • Use memoization & performance in a small program
  • Recognize and debug a common failure mode

Build the mental model

Memoization caches a pure function's results keyed by its arguments, so an expensive computation only runs once per unique input, no matter how many times it's called.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: Repeated calls with the same arguments are served from the cache

Why this matters

It's a direct, measurable performance win for expensive pure computations that get called repeatedly with the same inputs.

Real-world example

React's useMemo hook applies exactly this idea to avoid recomputing expensive derived values on every render.

Common mistakes

  • Memoizing an impure function whose result can change even with the same arguments
  • Letting the cache grow unbounded in a long-running process without any eviction
  • Using JSON.stringify as a cache key for arguments that include functions or circular structures

Try it yourself

Challenge

Use memoize to cache an expensive-looking square function and verify it's only computed once per input.

Practice

Knowledge check

Memoization is safe to apply to which kind of function?

Summary

Memoization caches a pure function's output by its arguments to avoid redundant, expensive recomputation.