Table of Contents

The icon of the Adeptus Mechanicus. A cog with a skull at the center.
A types letter.

Memoization

Last Tended

Status: sprout

Memoization is an optimization technique that is used on functions. When a memoised function is called, it caches what arguments it was passed & the output it returned. The next time it is called, it checks the cache to see if these new inputs are the same as the previous.

  • If they are, instead of preforming its calculation again, it just returns the return value it has in its cache
  • If they aren't, it performs its calculation & adds another record to its cache.

This means the function never performs its calculation on the same inputs twice. Reducing CPU time (at a cost of more memory). This technique is used when there is a computationally expensive function that was taking a long time to complete & impacting UX (User Experience).

Without Memoization

Below is an example of a function that takes a number, multiples it by 2, then returns the result. It also logs everytime it performs the calculation. We are calling this function 3 times. The 3rd call has the same argument as the 1st. You can see in the console that the function is calculating each time it is called.

/index.js

Console

const myFunc = (input) => {
    console.log(`calculating...`);
    const value = input * 2;
    return value;
};

myFunc(1);
myFunc(2);
myFunc(1);

With Memoization

Let memoise the function by defining a cache object our function will check everytime its called. Each time its called, it will:

  • do its calculation, return the value & add an entry to the cache or
  • return a value stored in the cache.

You can see in the console, the 3rd time we called the function (with the same input as the 1st call), no calculation was logged. Instead, the function just returned the value from the cache.

/index.js

Console

const cache = {};

const myFunc = (input) => {
    if (cache[input]) {
      return cache[input];
    };

    console.log(`calculating...`);
    const value = input * 2;
    cache[input] = value;
    return value;
};

myFunc(1);
myFunc(2);
myFunc(1);

Where to Next?

A sci-fi robot taxi driver with no lower body
└── JavaScript
└── Performance
├── Big O
├── Debounce Throttle
├── Loops
Arrow pointing down
YOU ARE HERE
├── Memoization
└── Web Workers