LRU 算法

249 阅读1分钟

什么是 LRU

LRU (Least recently used:最近最少使用)算法在缓存写满的时候,会根据所有数据的访问记录,淘汰掉未来被访问几率最低的数据。也就是说该算法认为,最近被访问过的数据,在将来被访问的几率最大。

image.png

  • 假设我们有一块内存,一共能够存储 5 数据块;
  • 依次向内存存入A、B、C、D、E,此时内存已经存满;
  • 再次插入新的数据时,会将在内存存放时间最久的数据A淘汰掉;
  • 当我们在外部再次读取数据B时,已经处于末尾的B会被标记为活跃状态,提到头部,数据C就变成了存放时间最久的数据;
  • 再次插入新的数据G,存放时间最久的数据C就会被淘汰掉;

算法实现

class LRUCache{
  list = []; // 用于标记顺序
  cache = {}; // 用于缓存数据
  capacity = 10; // 容量
  constructor(capacity){
    this.capacity = capacity;
  }

  // 存储数据
  put(key, value){
    // 如果已有数据
    if(this.cache[key] !== undefined){
      return this.get(key);
    }
    // 判断是否达到最大限制
    if(this.list.length >= this.capacity){
      const latest = this.list.shift();
      delete this.cache[latest];
    }
    // 缓存数据
    this.cache[key] = value;
    // 更新LRU数组
    this.list.push(key);
  }

  // 访问数据
  get(key){
    // 有数据
    if(this.cache[key] !== undefined){
      this.updateList(key);
      return this.cache[key];
    }
    return undefined;
  }

  // 更新LRU
  updateList(key){
    const idx = this.list.indexOf(key);
    if(idx > -1){
      this.list.splice(idx, 1);
    }
    this.list.push(key);
  }
}