DEV Community

Saurabh Bhan
Saurabh Bhan

Posted on

Memomization? how and the why in Javascript.

Memoization generally means to remember and in the world of programming a memoizing function is to make the function remeber the output value for a particular input, so if in future if the function is asked to run on the same input it delivers the results very fast as it already have the output for that input.

Let's take a look at the following diagram to understand better

Image description

in the diagram, we can see that if the function fib is memoizing(caching) the value for the calculations as the fibbonaci calculation are intense for higher numbers, we can see it only calculate once for that input and no matter how many time we run the function for the same input the output is given at an instant.

Heres the code for the above function.

const fib = (num) => {
    if(num < 2) return num
    return fib(num -1) + fib(num-2)
}
Enter fullscreen mode Exit fullscreen mode

This is the memoize decorator function we will be using

export const memoize = (fn) => {
    const cache = {};
    return (...args) => {
        if (JSON.stringify(args) in cache) {
            return cache[JSON.stringify(args)];
        }
        const result = fn(...args);
        cache[JSON.stringify(args)] = result;
        return result;
    }
}
Enter fullscreen mode Exit fullscreen mode

Running the function fib alone will occure in firing intensive calculations every single time. but if we wrap it in the memoize decorator fn it will calculate only one time and subsiquent runs will output results from the cache resulting in perfomant code and faster app.

const memoFib = memoize(fib)
Enter fullscreen mode Exit fullscreen mode

That is how you call and memoize the fib function this can be used with any other function aswell.

We generally use memoization on pure functions and intensive calculations, it can also be used in API calls but it is not recommended.

tldr; memoization is basically caching the results so that they can retrieved later and faster without making new calculations, with memoization we trade speed with meemory.

Top comments (0)