Find your content:

Search form

You are here

Learn about Memoize

 
Share

Introduction to memoize

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

Functions are an integral part of programming. They help add modularity and reusability to our code. We call the defined functions multiple times to get the expected result.

Lets take example of factorial function.

function factorial(n) {
// Calculations: n * (n-1) * (n-2) * ... (2) * (1)
return factorial
}

Great, now let’s find factorial(50). The computer will perform calculations and return us the final answer, sweet!

Lets run the factorial function again for 51 i.e factorial(51) now system again compute the value from beginning. Lets think about if we would have stored
previous execution value i.e factorial(50) then running factorial(51) might be even simpler

factorial(51) = factorial(50) * 51

But our function performs the calculations from scratch every time it’s called:

factorial(51) = 51 * 50 * 49 * ... * 2 * 1

Example memoize function

// a simple function to add something
const add = (n) => (n + 10);
add(9);
// a simple memoized function to add something
const memoizedAdd = () => {
let cache = {};
return (n) => {
if (n in cache) {
console.log('Fetching from cache');
return cache[n];
}
else {
console.log('Calculating result');
let result = n + 10;
cache[n] = result;
return result;
}
}
}
// returned function from memoizedAdd
const newAdd = memoizedAdd();
console.log(newAdd(9)); // calculated
console.log(newAdd(9)); // cached

My Block Status

My Block Content