最简单的LRU算法实现(TJ出品)
发布于 10 年前 作者 xingren23 5075 次浏览 最后一次编辑是 8 年前

在TJ的Connect模块中看到Cache中一个LRU算法,太简单了,一起品一下:

Cache.prototype.add = function(key){
  // initialize store
  var len = this.keys.push(key);//在数组最后添加一个元素

  // limit reached, invalidate LRU
  if (len > this.limit) this.remove(this.keys.shift());//删除数组的第一个元素

  var arr = this.store[key] = [];//这里为什么赋值为空数组???
  arr.createdAt = new Date;
  return arr;
};
5 回复

这个模块他都没怎么用吧。

staticCache即采用cache模块LRU算法,给出的性能测试数据如下:

  • static(): 2700 rps
  • node-static: 5300 rps
  • static() + staticCache(): 7500 rps staticCache比node-static快 29%,并且支持LRU算法。

因此组合使用static()+staticCache()应该能够获得更好的性能。【以上数据作者TJ的说明,我并没有验证】

生产环境上不行的

抛弃if (len > this.limit) this.remove(this.keys.shift());//删除数组的第一个元素 这段来看 后面的就是一个栈的数据存取的方式 可能是始终这个对象的keys的length固定在this.limit中 而var arr = this.store[key] = [];//这里为什么赋值为空数组??? this.keys.push(key) 添加对象的key var arr = this.store[key] = [] 根据当前的key定义一个数据结构

var arr = this.store[key] = [];//这里为什么赋值为空数组???

个人理解:将this.store[key]作为一个数组返回出去,外部可以做更多事情(相比字符串),灵活性好一点。

回到顶部