Explain Implement a memoization helper function
Last Updated :
10 May, 2022
What is memoization?
It is a programming technique that is used to increase the efficiency of function by storing the previous values that function has already been calculated.
It increases the program efficiency by caching the results of the function calls. We often waste time by calling the function again and again with the same parameter that had already been calculated. So we can store that calculated value and when the function is invoked with the same parameter then we just need to return that cached value.
Example 1: In this example, we'll see the working of memoization:
JavaScript
<script>
function mul(num1, num2) {
for (let i = 0; i < 10000000; i++) {
}
return num1 * num2;
}
console.log(mul(2, 3));
console.log(mul(2, 3));
</script>
Output:
6
6
Explanation: In this case, we are calculating the multiplication of two numbers but the function is taking time because of the for loop. And we are calling the function with the same parameters again and again. This is time wastage because we have already calculated the results of mul(2,3) and we are again calling it with the same parameter.
So, in this case, we can use the memoization technique to store the value of mul(2,3), and again when we will call the function with the same parameter then we will return the cached value.
Example 2: Let's see how much time does our function took to calculate the value of mul(2,3).
JavaScript
<script>
function mul(num1, num2) {
for (let i = 0; i < 10000000; i++) {
}
return num1 * num2;
}
console.time("Time taken");
console.log(mul(2, 3));
console.timeEnd("Time taken");
</script>
Output:
6
Time taken: 14.60ms
The function took 14.60 ms to calculate the multiplication of (2,3)
With the help of the memoization technique, we can increase the efficiency of the function by storing the value that function has already been calculated so that when we invoked the function with the same parameter then we will just return the cached value.
Example 3: Now let's say how we can use the memoization technique to reduce the time taken to execute the function with the same parameter again and again.
JavaScript
<script>
function memoizeFunction(func) {
let obj = {};
return function (a, b) {
const x = a.toString() + b.toString();
if (!obj[x]) {
obj[x] = func(a, b);
}
return obj[x];
}
}
function mul(num1, num2) {
for (let i = 0; i < 10000000; i++) {
}
return num1 * num2;
}
console.time("First time time taken");
let func = memoizeFunction(mul);
console.log(func(2, 3));
console.timeEnd("First time time taken");
console.time("Second time time taken");
func = memoizeFunction(mul);
console.log(func(2, 3));
console.timeEnd("Second time time taken");
console.time("Third time time taken");
func = memoizeFunction(mul);
console.log(func(2, 3));
console.timeEnd("Third time time taken");
</script>
Output:
6
First time, time taken: 24.73ms
6
Second time, time taken:22,17ms
6
Third time, time taken:8.30ms
NOTE: The amount of time it takes to complete a task may vary from time to time.
Explanation: In this case, we have used memoized function to cached the value that we have already been calculated. For the first time when we called func(2,3) then it will convert the parameter into string form and then stored it inside the object obj with the calculated value.
And when we called the func with the same parameter then at first it will check whether it already exists in the object obj or not. If it already exists then it will not calculate it again and will just return its value stored inside the object obj.
As we can see from the output that time to calculate the multiplication of 2 and 3 has decreased each time when we called the function with the same parameter.
Time is taken each time:
24.73 ms
22.17 ms
8.30 ms
So it's clear from the output that the memoization technique helped in reducing the time each time we called the function with the same parameter again and again.
Example 4: Let's see another example of using the memoization technique when calculating the Fibonacci number.
JavaScript
<script>
function memoizeFunction(func) {
let obj = {};
return function (a) {
const x = a.toString();
if (!obj[x]) {
obj[x] = func(a);
}
return obj[x];
}
}
function fibonacci(n) {
if (n === 0 || n === 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.time("First time, time taken");
let func = memoizeFunction(fibonacci);
console.log(func(10));
console.timeEnd("First time, time taken");
console.time("Second time, time taken");
func = memoizeFunction(fibonacci);
console.log(func(10));
console.timeEnd("Second time, time taken");
console.time("Third time, time taken");
func = memoizeFunction(fibonacci);
console.log(func(10));
console.timeEnd("Third time, time taken");
</script>
Output:
55
First time, time taken: 0.62ms
55
Second time, time taken: 0.28ms
55
Third time, time taken: 0.20ms
Advantages:
- With the help of memoization, we didn't need to re-calculate the value again and again
- It helps in reducing the time taken to execute the function when we called the function with the same parameter again and again
- It improves the performance
Disadvantages:
- It uses memory to speed up the execution of the function
- It puts extra burdens on the program
- Space overheads
Similar Reads
What are the Helper functions ?
The functions that perform some part of the computation of other functions are termed helper functions. They are named as per their work, i.e. they help the main function to look more clean, precise, and readable by giving descriptive names to some of the computations involved. Also, helper function
5 min read
Explain the MUL() function in JavaScript ?
The MUL function is a miniature of the multiplication function. In this function, we call the function that required an argument as a first number, and that function calls another function that required another argument and this step goes on. The first function's argument is x, the second function`s
1 min read
JavaScript Memoization
As our systems mature and begin to do more complex calculations, the need for speed grows, and process optimization becomes a need. When we overlook this issue, we end up with applications that take a long time to run and demand a large number of system resources.In this article, we are going to loo
5 min read
How to write a simple code of Memoization function in JavaScript ?
Memoization is a programming technique that we used to speed up functions and it can be used to do whenever we have an expensive function ( takes a long time to execute). It relies on the idea of cache {}. A cache is just a plain object. It reduces redundant function expression calls. Let's understa
3 min read
Function Notation Formula
A function is a type of operator that takes an input variable and provides a result. When one quantity is dependent on another, a function is created. An interesting property of functions is that each input corresponds to a single output. In other words, such an operator between two sets, say set A
4 min read
How to Recall a Function in Python
In Python, functions are reusable blocks of code that we can call multiple times throughout a program. Sometimes, we might need to call a function again either within itself or after it has been previously executed. In this article, we'll explore different scenarios where we can "recall" a function
4 min read
function command in Linux with examples
The function is a command in Linux that is used to create functions or methods. It is used to perform a specific task or a set of instructions. It allows users to create shortcuts for lengthy tasks making the command-line experience more efficient and convenient. The function can be created in the u
2 min read
Named Function Expression
In JavaScript or in any programming language, functions, loops, mathematical operators, and variables are the most widely used tools. This article is about how we can use and what are the real conditions when the Named function Expressions. We will discuss all the required concepts in this article t
3 min read
Implementing LRU Cache Decorator in Python
LRU is the cache replacement algorithm that removes the least recently used data and stores the new data. Suppose we have a cache space of 10 memory frames. And each frame is filled with a file. Now if we want to store the new file, we need to remove the oldest file in the cache and add the new file
3 min read
Explain the concept of memoization in pure components.
Memoization in React caches results in expensive function calls to save re-computation time. It's implemented via useMemo and React.memo, which memorize function outputs and component results respectively. This optimizes pure components, updating only when props or state change, boosting performance
2 min read