What is memoization and how to cache function results in JavaScript

featured Image

In this post, we will learn about Javascript memoization and how to write a memoize function in Javascript.

What is memoization in JavaScript?

Memoization is an optimization technique used to speed up computer programs. It is used to reduce time-consuming calculations by storing the results of the previous function in a cache and returning the cached values when the same input occurs again.

Let’s understand it with an example.

Suppose, we have a function that adds two numbers.

const add=(a,b)=>{
    return a + b
}

Now, whenever we run this function it consumes some time to do that calculation. We can just use the console.time() and console.timeEnd() to see the time.

console.time()
console.log(add(2,2))
console.timeEnd()

Output:

4
default: 4.878ms

It took approximately 4.878ms to do the calculation.

Now suppose we have to do the same calculation over and over again with the same argument.

console.log(add(2,2))
console.log(add(2,2))
console.log(add(2,2))

Here, we are invoking the same add() function with the same arguments 3 times, which means each time it will take 4.8ms (approx) time to calculate the same arguments.

This is time-consuming as we already know the results of the add function, which is 4 when the function is executed the first time.

So, rather than computing the addition 2 more times, we can just write a memoize function to store the results and use it when the same function is invoked the second time.

Write a memoization function in Javascript

This function will identify the function with its arguments. If the previous result of the function is stored in the cache object, then it will just return the results without executing the function again.

const memoize=(fn)=>{
  const cache = {}
  return function(...args){
    uniKey = fn.name+args[0]
    if(uniKey in cache){
      console.log('From the cache')
      return cache[uniKey]
    }else{
      let result = fn(...args)
      cache[uniKey] = result;
      return result
    }
  }
}

Here, we have a function called memoize, which takes in a function as an argument and returns another function that takes the arguments (...args).

Next, we have a cache object, which will store the values from the functions with a unique key (uniKey).

Here, we have concat the function name (fn.name) and the first argument of the function (args[0]) as a unique key just for the example.

 uniKey = fn.name+args[0]

Next, we have an if statement to check if the result of the function is in the cache object or not. If the unique key related to the function is found in the cache, it will return the result without invoking the function.

If not, then the add function passed to the memoize function will get executed inside the else block and the result will be stored with a unique key inside the cache object like this.

cache[uniKey] = result

Because of closure the returned function can access the function that is passed as an argument.

Now, let’s see an example, with memoize function implemented on function with same arguments.

const add=(a,b)=>{
    return a + b
}

const memoize=(fn)=>{
  const cache = {}
  return function(...args){
    uniKey = fn.name+args[0]
    if(uniKey in cache){
      console.log('From the cache')
      return cache[uniKey]
    }else{
      let result = fn(...args)
      cache[uniKey] = result;
      return result
    }
  }
}

const memoizeAdd = memoize(add)

console.time()
console.log(memoizeAdd(2,2))
console.timeEnd()

console.time()
console.log(memoizeAdd(2,2))
console.timeEnd()

Output:

4
default: 6.354ms

From the cache
4
default: 0.213ms

As you can see, the first time the function got invoked and it took 6.354ms to return the results.

And the next time, it only took 0.213ms because it returned the result from the cache without executing the add function again inside memoize function.

Conclusion: Here, we have learned what is Javascript memorization and how to use memoize to cache function results and speed up the program.


Other Articles You’ll Also Like:

Javascript nullish coalescing (double question mark) operator

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *