返回

LRU Cache算法:十分钟快速入门

前端

如何在十分钟内领略JS的LRU Cache算法(上)

随着各种在线服务和应用程序的迅速发展,缓存已成为必需。它可以在本地保留常用信息,从而提高应用程序的速度和响应能力。LRU Cache算法(最近最少使用缓存算法)是一种缓存算法,它在缓存已满时,会移除最近最少使用的项,以腾出空间给新的项。

本文包含

  • LRU Cache算法的基本概念和工作原理
  • LRU Cache算法的实现
  • 如何在真实场景中使用LRU Cache算法

LRU Cache算法的基本概念和工作原理

LRU Cache算法是一种基于链表的数据结构实现的缓存算法。它通过维护一个链表,将缓存中的项按最近使用顺序排列,最近使用过的项在链表的头部,最不经常使用的项在链表的尾部。当缓存已满时,LRU Cache算法会移除链表尾部的项,以腾出空间给新的项。

LRU Cache算法的实现

LRU Cache算法可以通过各种编程语言实现。以下是一个用JavaScript实现的LRU Cache算法:

class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.cache = new Map();
    this.head = null;
    this.tail = null;
  }

  get(key) {
    const node = this.cache.get(key);
    if (!node) {
      return null;
    }
    this.moveToHead(node);
    return node.value;
  }

  put(key, value) {
    const node = this.cache.get(key);
    if (node) {
      node.value = value;
      this.moveToHead(node);
    } else {
      const newNode = { key, value };
      this.cache.set(key, newNode);
      this.addToHead(newNode);
      if (this.cache.size > this.capacity) {
        this.removeTail();
      }
    }
  }

  moveToHead(node) {
    if (node === this.head) {
      return;
    }
    if (node === this.tail) {
      this.tail = node.prev;
      this.tail.next = null;
    } else {
      node.prev.next = node.next;
      node.next.prev = node.prev;
    }
    node.next = this.head;
    node.prev = null;
    this.head.prev = node;
    this.head = node;
  }

  addToHead(node) {
    node.next = this.head;
    node.prev = null;
    if (this.head) {
      this.head.prev = node;
    }
    this.head = node;
    if (!this.tail) {
      this.tail = node;
    }
  }

  removeTail() {
    const node = this.tail;
    this.tail = node.prev;
    this.tail.next = null;
    this.cache.delete(node.key);
  }
}

如何在真实场景中使用LRU Cache算法

LRU Cache算法可以在各种场景中使用,例如:

  • 浏览器缓存: 浏览器使用LRU Cache算法来缓存网页和资源,从而减少加载时间。
  • 数据库缓存: 数据库使用LRU Cache算法来缓存查询结果,从而提高查询速度。
  • CDN缓存: CDN使用LRU Cache算法来缓存静态文件,从而减少服务器负载。
  • 应用程序缓存: 应用程序可以使用LRU Cache算法来缓存数据,从而提高性能。