Memoization in JavaScript

Memoization is a method level caching technique. We can implement it in JS using the closure property of functions. And it is a very efficient technique, useful for recursive / repeatedly executing functions.

For example, in the following code block, Fibonacci function is called 453 times. 11 times we made call, and it calls itself 442 times.

let count = 0;

const fibonacci = function (n) {
    count++;
    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}

for (let i = 0; i <= 10; i += 1) {
    console.log(fibonacci(i));
}

console.log(`Without Memoization: ${count}`);
// Without Memoization: 453

But if we make use of memoization, we can reduce to 29 times (11 times we makes the call, and 18 times itself).

let count = 0;

const memoizer = function (cache, fn) {
    const shell = function (n) {
        count++;
        let result = cache[n];
        if (typeof result === 'undefined') {
            result = fn(shell, n);
            cache[n] = result;
        }
        return result;
    }
    return shell;
};

const cache = {
    0: 0,
    1: 1
};
const fibonacciMemo = memoizer(cache, (shell, n) => {
    return shell(n - 1) + shell(n - 2);
});

for (let i = 0; i <= 10; i += 1) {
    console.log(fibonacciMemo(i));
}

console.log(`With Memoization: ${count}`);
// With Memoization: 29


Leave a comment