Memoization

In JavaScript, memoization can be used to improve a program’s performance.

This is ideal whenever the same calculations (with the same inputs and outputs) are known to take place. Memoization helps by saving, or caching, these results in computer memory for later use. It can be applied to many contexts, including:

  • Making calls to recursive or pure functions where some calculations use the same inputs and return the same outputs.
  • Fetching from the server with the same base API endpoints.

Syntax

memo = []

function memoFunction(arg) {
  if(memo[arg]) {
    return memo[arg]
  } else {
    // Do this and update memo.
  }
}

Memoized results can be represented with arrays or objects. In a given function, if a previously calculated result exists in the memo array, it is returned. Otherwise, normal calculations take place and the memo array is updated.

Example

In the example below, the getSquare() function accepts a parameter n and returns the square of it. With small inputs, this function takes little to no time to process. But as the inputs get larger, the timelapse becomes more noticeable. This point is further shown with the calls to console.time() and console.timeEnd().

To address this, memoization is used in the getSquareMemo() function where such calculations are skipped if they have already been made and stored in memo.

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn JavaScript on Codecademy