javascipt使用缓存的例子
编辑时间:2020-12-31 作者:网络 浏览量:1290 来源:原创

最近有时间继续学习javascipt,https://zh.javascript.info/ 这个网站真不错。

学到缓存这里https://zh.javascript.info/call-apply-decorators#tou-ming-huan-cun 。绝对两个例子很好,转一下。

基本入门使用


<script>
"use strict";

function slow(x) {
  // 这里可能会有重负载的 CPU 密集型工作
  alert(`Called with ${x}`);
  return x;
}

function cachingDecorator(func) {
  let cache = new Map();

  return function(x) {
    if (cache.has(x)) {    // 如果缓存中有对应的结果
      return cache.get(x); // 从缓存中读取结果
    }

    let result = func(x);  // 否则就调用 func

    cache.set(x, result);  // 然后将结果缓存(记住)下来
    return result;
  };
}

slow = cachingDecorator(slow);

alert( slow(1) ); // slow(1) 被缓存下来了
alert( "Again: " + slow(1) ); // 一样的

alert( slow(2) ); // slow(2) 被缓存下来了
alert( "Again: " + slow(2) ); // 和前面一行结果相同
</script>
后来面向对象更加完善的例子。
<!DOCTYPE html>
<script>
"use strict";
let worker = {
  slow(min, max) {
    alert(`Called with ${min},${max}`);
    return min + max;
  }
};
function cachingDecorator(func, hash) {
  let cache = new Map();
  return function() {
    let key = hash(arguments); // (*)
    if (cache.has(key)) {
      return cache.get(key);
    }
    let result = func.call(this, ...arguments); // (**)
    cache.set(key, result);
    return result;
  };
}
function hash(args) {
  return args[0] + ',' + args[1];
}
worker.slow = cachingDecorator(worker.slow, hash);
alert( worker.slow(35) ); // works
alert( "Again " + worker.slow(35) ); // same (cached)
</script>


来说两句吧