Memoization?

In this blog post, we will explore memoization, its advantages, and common real-world use cases. We will also see how to implement memoization using vanilla JavaScript without any library.

What is Memoization?

Memoization is a technique in computer programming that is used to speed up the execution of a function by caching the results of expensive computations. In JavaScript, memoization can be applied to any function that has expensive computation and is called frequently. When a function is called with a particular set of input parameters, the result is stored in a cache. If the same function is called with the same input parameters again, the cached result is returned instead of recomputing the result.

Advantages of Memoization

The main advantage of memoization is that it can significantly improve the performance of a function. If a function is called frequently with the same input parameters, memoization can save a lot of computation time by caching the result and returning it from the cache instead of recomputing it.

Memoization can also help to reduce the complexity of code by separating the calculation of a result from the logic that uses the result. This can make code easier to understand, maintain and debug.

Real-world Use Cases of Memoization

Memoization can be used in a wide range of real-world scenarios where a function is called repeatedly with the same input parameters. Some common examples include:

Recursive Functions

Recursive functions are functions that call themselves with different input parameters. If the same input parameters are used multiple times, memoization can prevent the function from re-computing the same results repeatedly.

Database Queries

Memoization can be used to cache the results of database queries. If a database query is called multiple times with the same input parameters, memoization can prevent the database from being queried multiple times and speed up the response time.

API Calls

Memoization can be used to cache the results of API calls. If an API call is called multiple times with the same input parameters, memoization can prevent the API from being called multiple times and speed up the response time.

Implementation of Memoization in JavaScript

Implementing memoization in JavaScript is simple. We will see how to implement memoization using a Fibonacci function that calculates the nth Fibonacci number.

Below is the code for calculating the Fibonacci number without memoization:

function fibonacci(n) {
  if (n < 2) {
    return n;
  } else {
    return fibonacci(n - 1) + fibonacci(n - 2);
  }
}

This function calculates the nth Fibonacci number recursively. The problem with this function is that it recalculates the same values repeatedly, which can lead to a significant performance hit for larger values of n.

Let's implement a generic memoize that could be used for any use cases.

function memoize(func) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache[key]) {
      return cache[key];
    }
    const result = func.apply(this, args);
    cache[key] = result;
    return result;
  };
}

When the memoize function is called with input parameters, it first checks whether the result for those parameters is already present in the cache. If it is, it returns the cached result. If not, it calls the original function with those input parameters and stores the result in the cache for future use.

Below is how you can use the memoize function to improve the Fibonacci function.

const fibonacci = memoize(function (n) {
  const fibonacciHelper = memoize(function (n) {
    if (n < 2) {
      return n;
    }
    return fibonacciHelper(n - 1) + fibonacciHelper(n - 2);
  });
  return fibonacciHelper(n);
});

When the fibonacci function is called with the same input parameters, the result is returned from the cache instead of recalculating it, making the function much more efficient.

How do they compare?

We will compare how many times a function is called when we use memoization and when we don't use memoization. Let's say we run the following inputs:

Inputsfibonacci without memofibonacci with memo
111
233
354
495
5156
6257
7418
8679
910910
1017711

You can see the clear benefit of using the memoization. As the input gets larger, there is a huge benefit in caching/memoizing the results.

NOTE: It's not recommended to apply memoization unnecessarily in all scenarios as that will bring in increased memory usage.

I hope this article was helpful to you. If yes, please make sure to read my other articles. I am currently writing a series on common "Frontend engineering interview questions" based on my experience interviewing people at Amazon, RedHat, VMware, and Snapdeal, ...

Please subscribe to the newsletter to get the articles delivered directly to your mailbox.

Cheers

Arunkumar Sri Sailapathi.

#2Articles1Week