| 1. |
What is memoization? |
|
Answer» Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned.
Consider the following function: function addTo256(num){return num + 256; } addTo256(20); // Returns 276 addTo256(40); // Returns 296 addTo256(20); // Returns 276 In the code above, we have written a function that adds the parameter to 256 and returns it. This is where memoization comes in, by using memoization we can store(cache) the computed results based on the parameters. If the same parameter is used again while invoking the function, instead of computing the result, we directly return the stored (cached) value. Let’s convert the above function addTo256, to a memoized function: function memoizedAddTo256(){var cache = {}; return function(num){ if(num in cache){ console.log("cached value"); return cache[num] } else{ cache[num] = num + 256; return cache[num]; } } } var memoizedFunc = memoizedAddTo256(); memoizedFunc(20); // Normal return memoizedFunc(20); // Cached return In the code above, if we run the memoizedFunc function with the same parameter, instead of computing the result again, it returns the cached result.
|
|