zoukankan      html  css  js  c++  java
  • 缓存函数 memorize

    // 缓存函数
    Function.prototype.memoize = function () {
      var _this = this;
      return function () {
        const args = Array.prototype.slice.call(arguments);
        _this.cache = _this.cache || {};
        return _this.cache[args] ? _this.cache[args] : (_this.cache[args] = _this.apply(this, args))
      }
    }
    
    // 耗时函数
    function sleep(time) { return new Promise(resolve => setTimeout(resolve, time)) }
    
    // 测试消耗时间
    function test(func, ...args) {
      let result = null;
      let start = new Date().getTime();
      result = func.call(null, ...args)
      return result.then(() => {
        console.info(...args)
        let end = new Date().getTime();
        console.info((end - start) + "ms")
      })
    }
    
    (async function () {
      let s = sleep.memoize()
      await test(s, 2500)    // 第一次执行2500参数的耗时 2500ms
      await test(s, 2500)    // 第二次执行2500参数的耗时 0ms 被缓存了
      await test(s, 1500)    // 第一次执行1500参数的耗时 1500ms
      await test(s, 2500)    // 第三次执行2500参数的耗时 0ms 被缓存了
      await test(s, 1500)    // 第二次执行1500参数的耗时 0ms 被缓存了
      console.info('sleep', sleep.cache); // 打印缓存的参数对应值
    })()

    参考:https://www.jianshu.com/p/9af1c9c3a02b

  • 相关阅读:
    Oracle 函数
    ecplise 修改编码
    mysql json 使用 类型 查询 函数
    java 子类强转父类 父类强转子类
    java UUID
    Java Number & Math 类
    java String类
    apache StringUtils 工具类
    apache ArrayUtils 工具类
    java Properties
  • 原文地址:https://www.cnblogs.com/leyi/p/14637973.html
Copyright © 2011-2022 走看看