liveBook · Manning

Memoization

As explained in Secrets of the JavaScript Ninja, Second Edition

A technique that stores computed results so repeated calls with the same inputs can reuse them.

Memoization lets a function reuse a result instead of recalculating it. Store each result alongside its input; when the same input comes around again, return the cached result. In JavaScript, a function property can hold the cache. section 3.2.2 section 3.2

A self-memoizing function follows this cycle:

  • Create the cache the first time the function is called. section 3.2.2
  • Check whether the input already has a cached result; return it if found. section 3.2.2
  • Otherwise, calculate the result, store it with the input, and return it. The cache remains as long as the function does. section 3.2.2

Caching a prime-number check

The isPrime function stores true or false for each value it checks. Assertions verify both that 5 is prime and that its answer was cached. section 3.2.2

Listing 3.3. Memoizing previously computed values
function isPrime(value){
  if (!isPrime.answers){                         #A
    isPrime.answers = {};                        #A
  }                                              #A

  if (isPrime.answers[value] !== undefined) {            #B
    return isPrime.answers[value];                       #B
  }                                                      #B
  
  var prime = value !== 1; // 1 is not a prime
 
  for (var i = 2; i < value; i++) {
    if (value % i === 0) {
      prime = false;
      break;
    }
  }
  return isPrime.answers[value] = prime;                   #C 
}

assert(isPrime(5), "5 is prime!" );                        #D
assert(isPrime.answers[5], "The answer was cached!" );     #D

See the complete isPrime implementation, including cache initialization, lookup, and result storage. section 3.2.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains cache initialization, lookup, and storage through a single prime-checking function.
Examples
Uses prime testing and names animation calculations, stable-data searches, and time-consuming math as use cases.
What you can do after
Apply memoization in JavaScript by caching results on a function and reusing them for repeated inputs.
How it connects
Connects memoization to JavaScript functions as objects and function properties.

Also explained in

Compare how 8 books explain memoization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.