缓存功能的结果?

问题描述:

在Javascript中,有一种方法可以缓存以下功能的结果:

In Javascript, is there a way to cache results for functions that are:


  • a)。计算上很昂贵。

  • b)。多次调用。

例如,经常调用递归阶乘函数。通常,我会创建一个单独的数组,例如 facotrialResults = []; 并在计算它们时将结果添加到它们中, factorialResults [x] =结果; 但是,有没有一种更好的方法可以完成此缓存而无需在全局名称空间中添加新变量?

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.

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 = {};

这将要求该函数是1-1函数且无副作用。

This would require that the function is a 1-1 function with no side effects.