In Javascript, is there a way to cache results for functions that are:
- a). Computationally expensive.
- b). Called multiple times.
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?
You could attach a hash to the function that you want to cache.
This would require that the function is a 1-1 function with no side effects.
You could consider rolling the underscore library into your environment. It's useful for many things, including its memoize function
using cache
it's general solution
You can define your own function properties so that the cached results are associated with the function, rather than populating the global namespace in a new array:
The only problem with this is the overhead of checking if the result has been cached. However, if the complexity of the check is much lower than recomputing the problem, then it is well worth it.