Memoization Simplified

rv90904

Ramesh Vishnoi

Posted on April 1, 2023

Memoization Simplified

One of the common interview question asked during interview is memoization.

Before starting on technical details, lets understand general definition -

Memoization is a programming technique that speeds up the execution of functions by caching the results of previous function calls and returning the cached result when the same inputs occur again.
This can be useful for functions that take a long time to compute and are called repeatedly with the same inputs. By caching the results of previous function calls, memoization avoids redundant computations and improves the overall performance of the function.

In simple words, memoization is a process where we cache the result of a function against function's input arguments and use cached value when same input arguments are used.

Implementation :
You can create generic function which coverts a normal function into memoized function.

Consider the following example - Assume you have a expensive function which multiply 2 big integers

const multiply = (a, b) => {
    return a * b;
}
Enter fullscreen mode Exit fullscreen mode

There is no point in calling this function again and again with same arguments. You can just create a memoized version of same function which will save you execution time and computational space.

In order to achieve this, we need to use High Order Functions. Find more information on HOF here

const memoizedFunction = (func) => {
        let cache = {}
        return (...args) => {
            var stringifiedArgs = args.toString();
            if (cache[stringifiedArgs]) {
                return cache[stringifiedArgs]
            }

            var result = func(...args)
            cache[stringifiedArgs] = result;
            return result;
        }
}
Enter fullscreen mode Exit fullscreen mode

Here memoizedFunction accepts function as argument and return a new funtion. It also maintain history of all the function call and its value inside cache which is then used to determine if it need to call the function or return value from cache.

const memoizedMultiply = memoizedFunction(multiply)


memoizedMultiply(314, 340) // calculated
memoizedMultiply(10, 340) // calculated
memoizedMultiply(314, 340) // cached

Enter fullscreen mode Exit fullscreen mode

Voila! You have successfully memoized a function.

If you're interested in learning more about React, React Native and JS, check out my Linkedin profile here. And feel free to share it with anyone who might find it helpful!

Happy coding!

💖 💪 🙅 🚩
rv90904
Ramesh Vishnoi

Posted on April 1, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related