DEV Community

loading...

Memoization in JavaScript

bishnucit profile image Bishnu Prasad Chowdhury ・1 min read

Memoization is a process by which a recursive function call can be improved more like creating an index for already computed values.

Before doing a costly function call where it computes some value an index function is called where all previous outputs of the function are stored. If the required calculation is already present in the existing index it returns the result instead of wasting the resource to calculate the result again.

It is kind of an optimization using which we can save resources and time to compute.

This is achievable because of closure in JavaScript, we can return the indexed result instead of calculated result using an inner function.

// A simple function

var a = (x) => (x * 2)
a(2);
>4

// Now let's memoize the func

var mem_a = () => {
    var index = {};
    return (x) => {
        if( x in index){
            return index[x];
        } else {
            var b = x *2;
            index[x] = b;
            return b;
        }
     }
}

var c = mem_a();
// Does calculation
console.log(c(5));
> 10
// Uses memoization
console.log(c(5));
> 10

Enter fullscreen mode Exit fullscreen mode

It stores result in memory so we should avoid it for function which are called frequently and also we should not index the errors thrown by the calculation if any.

So to sum it up this is like wasting memory to reduce execution time of an expensive function.

Discussion (0)

pic
Editor guide