Memoization in JavaScript - Shorts

Memoization in JavaScript - Shorts

Written by Rahul on Oct 26th, 2021 Views Report Post

In my recent tweet, I said to Use Memoization to make your JavaScript functions more efficient.

<script></script>

So in this post, I'm going to discuss with you What is Memoization in JavaScript.


Memoization is an optimization technique used to speed up programs by storing the results of function calls and returning the cached result when the same inputs occur again.

It works if the result of calling a function with the same set of arguments results in the same output. In other words, the function must be pure, otherwise caching the result would not make sense.

Why is Memoization useful?

Suppose our function takes 1 second to run while caching lets us speed up the process to 2 milliseconds 😳.

When to Memoize your function?

The best use case of memoized functions is for heavy computational functions.

  • Function should be pure so that it returns the same output each time it are called with a particular input.
  • Functions should have a limited input range so that cached values can be made use of more frequently.
  • Recursive function with recurring input values.

Example:

const memoizedAdditon = () => {
    let cache = {}; 
    return (n) => {
        if (n in cache) {
            console.log('Fetching from cache'); 
            return cache[n]; 
        }
        else {
            console.log('Calculating result'); 
            const result = n + 1; 
            cache[n] = result; 
            return result; 
        }
    }
}

const addition = memoizedAdditon(); 
console.log(addition(7)); // Calculating result 8
console.log(addition(7)); // Fetching from cache 8
console.log(addition(7)); // Fetching from cache 8

🚀Thanks For Reading | Happy Coding⚡

Comments (0)