What is Memoization in JavaScript ?
Last Updated :
07 Feb, 2024
Memoization is an optimization technique used in computer programming to store the results of expensive function calls and return the cached result when the same inputs occur again. This can help to improve performance by avoiding redundant calculations. In JavaScript, memoization can be implemented using closures or by leveraging data structures like objects or maps to store previously computed results.
Example: Here, The fibonacci
function takes an integer n
as input, representing the position in the Fibonacci sequence to compute. Inside the function, it first checks if the result for the given n
is already cached in the memo
object. If it is, it returns the cached result. If the result is not cached, it calculates the Fibonacci number recursively by calling itself with the two previous Fibonacci numbers (n - 1
and n - 2
) and stores the result in the memo
object. Finally, it returns the computed Fibonacci number.
Javascript
function fibonacci(n, memo = {}) {
if (n in memo) {
return memo[n];
}
if (n <= 2) {
return 1;
}
memo[n] = fibonacci(n - 1, memo)
+ fibonacci(n - 2, memo);
return memo[n];
}
console.log(fibonacci(6));
console.log(fibonacci(10));
console.log(fibonacci(20));
|
Share your thoughts in the comments
Please Login to comment...