缓存函数的结果?

时间:2012-07-25 23:50:32

标签: javascript caching

在Javascript中,有没有办法缓存以下函数的结果:

  • a)中。计算上很昂贵。
  • B)。多次打电话。

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

4 个答案:

答案 0 :(得分:4)

您可以将哈希附加到要缓存的函数。

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功能,没有副作用。

答案 1 :(得分:2)

您可以定义自己的函数属性,以便缓存的结果与函数关联,而不是在新数组中填充全局命名空间:

function factorial(n) {
  if (n > 0) {
    if (!(n in factorial))  // Check if we already have the result cached.
      factorial[n] = n * factorial(n-1);
    return factorial[n];
  }
  return NaN;
}
factorial[1] = 1; // Cache the base case.

唯一的问题是检查结果是否已被缓存的开销。但是,如果检查的复杂性远低于重新计算问题,那么这是值得的。

答案 2 :(得分:2)

您可以考虑将underscore库滚动到您的环境中。它对很多东西很有用,包括它的memoize函数

  

通过缓存计算结果来记忆给定函数。对...有用   加快慢速运行计算。如果传递了可选项   hashFunction,它将用于计算用于存储的哈希键   结果,基于原始函数的参数。默认   hashFunction只使用memoized函数的第一个参数   关键。

var fibonacci = _.memoize(function(n) {
  return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

答案 3 :(得分:0)

使用缓存

这是一般解决方案

// wrap cache function
var wrapCache = function(f, fKey){
    fKey = fKey || function(id){ return id; };
    var cache = {};

    return function(key){
        var _key = fKey(key); 
        if (!cache[_key]){
            cache[_key] = f(key);
        };

        return cache[_key];
   };
};

// functions that expensive
var getComputedRGB = function(n){
    console.log("getComputedRGB called", n) ;
    return n * n * n; 
};

// wrapping expensive
var getComputedRGBCache = wrapCache(getComputedRGB, JSON.stringify);


console.log("normal call");
console.log(getComputedRGB(10));
console.log(getComputedRGB(10));
console.log(getComputedRGB(10));
console.log(getComputedRGB(10));
// compute 4 times


console.log("cached call") ;
console.log(getComputedRGBCache(10));
console.log(getComputedRGBCache(10));
console.log(getComputedRGBCache(10));
console.log(getComputedRGBCache(10));
// compute just 1 times


// output
=> normal call 
getComputedRGB called 10
1000
getComputedRGB called 10
1000
getComputedRGB called 10
1000
getComputedRGB called 10
1000

=> cached call
getComputedRGB called 10
1000
1000
1000
1000
相关问题