LRU
LRU(Least Recently Used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据。核心思想是如果数据最近被访问过,那么将来被访问的几率也会高。
- 新数据插入到表头
- 每当缓存命中(即缓存数据被访问),则将数据移动到表头部
- 当表达到限制长度的时候,将表尾部的数据丢弃
实现代码如下:
cache使用数组作为存储容器
class LRUCache{ constructor(size = 5){ this.size = size this.cache = [] } get(key){ let index = this.cache.findIndex(item => item.key === key) if(index === -1){ return -1 } let value = this.cache[index].value if(index > 0){ this.cache.splice(index,1) this.cache.unshift({key,value}) } return value } set(key,value){ let index = this.cache.findIndex(item => item.key === key) if(index === -1){ if(this.cache.length >= this.size){ this.cache.pop() } this.cache.unshift({key,value}) }else{ if(index > 0){ this.cache.splice(index,1) this.cache.unshift({key,value}) } } } }
cache使用map作为存储容器
class LRUCache { constructor(size = 5){ this.cache = new Map() this.size = size } } LRUCache.prototype.get = function (key) { if (this.cache.has(key)) { // 存在即更新 let value = this.cache.get(key); this.cache.delete(key); this.cache.set(key, value); return value; } return null; }; LRUCache.prototype.set = function (key, value) { if (this.cache.has(key)) { // 存在即更新(删除后加入) this.cache.delete(key); } else if (this.cache.size >= this.size) { // 不存在即加入 // 缓存超过最大值,则移除最近没有使用的 this.cache.delete(this.cache.keys().next().value); } this.cache.set(key, value); };
如果cache使用数组作为存储容器,在get/set时应注意index = 0时的处理逻辑,但如果使用map作为存储容器的话,则不需考虑。
以自己现在的努力程度,还没有资格和别人拼天赋