Memoization is an optimization technique that is used to improve the performance of a function by caching its return values so that it does not need to redo the potentially heavy computations next time it is called.
Note: Not all functions can be memoized; only referential transparent functions
EXAMPLE:.
Generally consider caliculating Fibonacci number.. general javascript code looks as:
function getFibonacci (num) {
if (num < 2) {
return num;
}
return getFibonacci(num - 1) + getFibonacci(num - 2);
}
alert(getFibonacci(10)); // => 55 (with 177 iterations) But using Momorizing concept we can achieve it very simpley in less Iterations by declaring a cache array where we can store the already-calculated function values that were returned in previous calls.
Then, instead of invoking the function,we can return these values in subsequent calls to the function..
function getFibonacci (num) {
var cache = [];
var fib = function(value) {
if(value < 2 ) return value;
if( cache[value] ) return cache[value];
cache[value] = (fib(value -1)) + (fib(value-2));
return cache[value];
};
return fib(num);
}
alert(getFibonacci(10)); // => 55 (with 20 iterations)