什么是 LRU

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

代码实现

核心原理:每次添加一个数据时,都去缓存(这里假设用队列的先进先出思想来模拟实现)中查找是否存在,如果存在就直接使用该缓存数据,同时把该缓存数据挪到队列的尾部,如果不存在,需要先判断当前缓存存放的数据是否已满,如果满了就先删除队列头部的数据,然后把新的数据添加进缓存中(队列的尾部)。

  1. class LRUCache{
  2. constructor(capacity){
  3. this.capacity = capacity;
  4. this.cache = new Map();
  5. }
  6. get(key){
  7. if(!this.cache.has(key)) return -1;
  8. const value = this.cache.get(key);
  9. this.cache.delete(key);
  10. this.cache.set(key, value);
  11. return value;
  12. }
  13. set(key, value){
  14. if(this.cache.has(key)){
  15. this.cache.delete(key);
  16. }else{
  17. if(this.cache.size === this.capacity){
  18. // 获取到Map中第一个数据的key值,即最近最少访问的key,删之
  19. const delKey = this.cache.keys().next().value;
  20. this.cache.delete(delKey);
  21. }
  22. }
  23. this.cache.set(key, value);
  24. }
  25. }

题目

LRU 缓存

参考

缓存文件置换机制
Cache replacement policies

什么是 LFU