可用map实现lru缓存:利用map插入顺序特性,get/set时将key移至末尾,超限时删除首个key;封装为lrucache类,支持容量限制、has/delete/clear方法,并可扩展ttl功能。

可以用 Map 实现 LRU(最近最少使用)缓存,核心思路是:每次读写都把对应 key 移到末尾,容量超限时删除最前面的项。
利用 Map 的插入顺序特性
Map 会按插入顺序遍历,且 delete + set 一次操作就能把某个 key “移到末尾”。这比用普通对象或 Object.keys() 排序高效得多。
- 新增/访问时调用
map.set(key, value)—— 自动放到末尾 - 要淘汰时取
map.keys().next().value—— 拿到最早插入(即最久未用)的 key - 用
map.delete(oldestKey)删除它
封装一个带容量限制的 LRU 缓存类
下面是一个轻量、可直接使用的实现:
<font size="2"><pre class="brush:php;toolbar:false;">class LRUCache {
constructor(maxSize = 10) {
this.map = new Map();
this.maxSize = maxSize;
}
get(key) {
if (!this.map.has(key)) return undefined;
const value = this.map.get(key);
this.map.delete(key); // 先删
this.map.set(key, value); // 再加,挪到末尾
return value;
}
set(key, value) {
if (this.map.has(key)) {
this.map.delete(key);
} else if (this.map.size >= this.maxSize && this.maxSize > 0) {
// 淘汰最老的一项
const oldestKey = this.map.keys().next().value;
this.map.delete(oldestKey);
}
this.map.set(key, value);
}
has(key) {
return this.map.has(key);
}
delete(key) {
return this.map.delete(key);
}
clear() {
this.map.clear();
}
}
使用示例:
<font size="2"><pre class="brush:php;toolbar:false;">const cache = new LRUCache(3);
cache.set('a', 1);
cache.set('b', 2);
cache.set('c', 3);
cache.get('a'); // 访问 a,a 变成最新
cache.set('d', 4); // 此时 b 是最老的,被踢出 → map: {'c'→3, 'a'→1, 'd'→4}
注意边界与优化点
- maxSize ≤ 0 时禁用淘汰:适合仅做临时存储、不设上限的场景
-
避免频繁调用
keys().next():虽是 O(1),但创建迭代器有轻微开销;生产环境若性能敏感,可额外维护一个指向头节点的引用(需改用链表结构) - key 类型要谨慎:Map 支持任意类型作 key,但缓存通常用字符串或 symbol;若用对象作 key,要注意引用相等性,容易导致“存了查不到”
-
不自动处理过期时间:这是纯 LRU,如需 TTL(存活时间),得额外存时间戳并在
get时检查
简单扩展:支持 TTL 的混合策略
只需在值中包裹时间信息,get 时判断是否过期:
<font size="2"><pre class="brush:php;toolbar:false;">set(key, value, ttlMs = Infinity) {
const expiresAt = Date.now() + ttlMs;
if (this.map.has(key)) this.map.delete(key);
else if (this.map.size >= this.maxSize && this.maxSize > 0) {
const oldestKey = this.map.keys().next().value;
this.map.delete(oldestKey);
}
this.map.set(key, { value, expiresAt });
}
get(key) {
if (!this.map.has(key)) return undefined;
const entry = this.map.get(key);
if (Date.now() > entry.expiresAt) {
this.map.delete(key);
return undefined;
}
// 命中后仍需更新位置(保持 LRU 语义)
this.map.delete(key);
this.map.set(key, entry);
return entry.value;
}Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











