In Javascript, is there a way to cache results for functions that are:
Take for example a recursive factorial function that gets called frequently. Usually I'd create a separate array such as facotrialResults = [];
and add my results to them when I calculate them, factorialResults[x] = result;
However, is there a better way to accomplish this caching without the use of adding a new variable to the global namespace?
Memoization allows you to optimize a Python function by caching its output based on the parameters you supply to it. Once you memoize a function, it will only compute its output once for each set of parameters you call it with. Every call after the first will be quickly retrieved from a cache.
A result cache is an area of memory, either in the Shared Global Area (SGA) or client application memory, that stores the results of a database query or query block for reuse. The cached rows are shared across SQL statements and sessions unless they become stale.
The data in a cache is generally stored in fast access hardware such as RAM (Random-access memory) and may also be used in correlation with a software component. A cache's primary purpose is to increase data retrieval performance by reducing the need to access the underlying slower storage layer.
cache can do much more (it works on function with any arguments, properties, any type of methods, and even classes...).
You could attach a hash to the function that you want to cache.
var expensive_fn = function(val) {
var result = arguments.callee.cache[val];
if(result == null || result == undefined) {
//do the work and set result=...
arguments.callee.cache[val]=result;
}
return result;
}
expensive_fn.cache = {};
This would require that the function is a 1-1 function with no side effects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With