· 2 min read Comments

Write efficient function in JavaScript: What is Memoization?

  1. Calligraphy Authors's Headshot
    Rahulism

    Owner


Table Of Contents


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.

Use Memoization to make your JavaScript functions more efficient — RAHUL (@rahxul) March 31, 2021

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.

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⚡


Share on:
Ashish Lahoti avatar
About Rahulism
I’m a front-end Developer and Blogger. Focused more on User Experience. I’m Passionate about startups