DEV Community

 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on

1 2

Memoization in JavaScript

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay