lru-cache、quick-lru 和 @alloc/quick-lru 都是用于在 JavaScript 环境中实现最近最少使用(LRU)缓存策略的库。它们旨在帮助开发者管理内存,防止数据无限增长,同时保持对热点数据的高速访问。lru-cache 是生态系统中最成熟、功能最丰富的选择,支持复杂的过期策略和异步操作;quick-lru 则以极简主义著称,专注于核心缓存功能,体积更小;@alloc/quick-lru 是 quick-lru 的一个分支版本,通常用于特定工具链的内部依赖或修复特定问题。
在构建高性能 JavaScript 应用时,缓存是优化性能的关键手段之一。最近最少使用(LRU)算法是最常用的缓存淘汰策略。在 npm 生态中,lru-cache、quick-lru 和 @alloc/quick-lru 是三个常见的选择。虽然它们的核心目标一致,但在设计理念、功能集和维护状态上存在显著差异。本文将从架构师的角度,深入分析这三者的技术细节,帮助你在实际工程中做出正确选择。
这三个库都提供了基于 Map 的 API,但在初始化配置和实例化方式上有所不同。
lru-cache 提供了最丰富的配置选项。它支持通过 max 限制条目数量,也支持通过 maxSize 限制内存大小(需配合 sizeCalculation)。
// lru-cache
import { LRUCache } from 'lru-cache';
const cache = new LRUCache({
max: 500,
maxSize: 5000000,
sizeCalculation: (value, key) => value.length,
ttl: 1000 * 60 * 5 // 5 分钟过期
});
cache.set('key', 'value');
const val = cache.get('key');
quick-lru 的设计哲学是极简。它主要关注 maxSize(最大条目数),配置项非常少,适合快速上手。
// quick-lru
import QuickLRU from 'quick-lru';
const cache = new QuickLRU({
maxSize: 500
});
cache.set('key', 'value');
const val = cache.get('key');
@alloc/quick-lru 作为 quick-lru 的分支,其 API 与原版 quick-lru 保持高度一致,旨在保持兼容性。
// @alloc/quick-lru
import QuickLRU from '@alloc/quick-lru';
const cache = new QuickLRU({
maxSize: 500
});
cache.set('key', 'value');
const val = cache.get('key');
在生产环境中,缓存条目不能永远存在。如何处理过期数据是区分库成熟度的重要指标。
lru-cache 内置了强大的时间控制功能。它支持 ttl(Time To Live),允许设置全局默认过期时间或单个条目的过期时间。它还支持 noDisposeOnSet 等高级选项来控制清理回调。
// lru-cache: 支持 TTL 和 清理回调
const cache = new LRUCache({
ttl: 1000 * 60, // 默认 1 分钟过期
dispose: (value, key) => {
console.log(`清理 ${key}`);
}
});
cache.set('temp', 'data', 1000 * 30); // 单独设置 30 秒过期
quick-lru 在核心版本中 不支持 基于时间的自动过期。它纯粹基于访问顺序和最大数量进行淘汰。如果需要时间过期,开发者需要自己包装一层逻辑或使用 has 检查时间戳。
// quick-lru: 无内置 TTL,需手动管理
const cache = new QuickLRU({ maxSize: 100 });
// 开发者需自行存储时间戳并验证
cache.set('key', { value: 'data', timestamp: Date.now() });
@alloc/quick-lru 同样继承了 quick-lru 的轻量特性,通常 不包含 内置的时间过期机制。它的设计目标是保持快速和简单,将复杂逻辑留给上层应用。
// @alloc/quick-lru: 同样无内置 TTL
const cache = new QuickLRU({ maxSize: 100 });
// 行为与 quick-lru 一致,专注于内存淘汰
当需要遍历缓存内容或检查键是否存在时,各库的表现也不同。
lru-cache 完全遵循 ES6 Map 的迭代器协议。你可以直接使用 for...of 循环,它也提供了 keys(), values(), entries() 方法。
// lru-cache: 完整的迭代器支持
for (const [key, value] of cache) {
console.log(key, value);
}
const keys = Array.from(cache.keys());
quick-lru 也提供了类似的迭代器支持,使其能够像 Map 一样使用,这大大降低了迁移成本。
// quick-lru: 支持迭代器
for (const [key, value] of cache) {
console.log(key, value);
}
const hasKey = cache.has('key');
@alloc/quick-lru 保持了与 quick-lru 相同的迭代行为,确保在替换依赖时不会破坏现有的遍历逻辑。
// @alloc/quick-lru: 兼容的迭代行为
for (const [key, value] of cache) {
console.log(key, value);
}
除了基本的 get 和 set,企业级应用往往需要更多控制。
lru-cache 支持异步操作(fetchMethod),允许在缓存未命中时自动触发异步加载函数。它还支持 allowStale,允许在后台更新时返回旧数据,这对高可用性系统至关重要。
// lru-cache: 异步获取与脏读支持
const cache = new LRUCache({
max: 100,
fetchMethod: async (key, staleValue, { options }) => {
return await db.query(key);
},
allowStale: true
});
// 自动触发 fetchMethod 如果缓存缺失
const data = await cache.fetch('user:123');
quick-lru 没有内置异步获取或脏读功能。它的设计是同步的、纯粹的。这意味如果你需要异步加载,必须在外部处理逻辑。
// quick-lru: 纯同步,无内置异步获取
const data = cache.get('user:123');
if (!data) {
const fresh = await db.query('user:123');
cache.set('user:123', fresh);
}
@alloc/quick-lru 同样保持同步和纯粹。它不引入额外的复杂性,适合作为底层基础库被其他工具调用。
// @alloc/quick-lru: 纯同步
const data = cache.get('user:123');
// 外部处理异步逻辑
选择库时,维护状态是架构决策中的关键风险因素。
lru-cache 由 Node.js 核心贡献者维护,是 Node.js 生态中最依赖广泛的缓存库之一。它更新频繁,对 TypeScript 支持良好,并且积极修复安全漏洞和性能问题。它是大多数大型框架的首选依赖。
quick-lru 由知名开发者 Sindre Sorhus 维护,状态稳定。虽然更新频率不如 lru-cache 高,但其代码库小,逻辑简单,风险较低。它在许多前端工具中广泛使用。
@alloc/quick-lru 是一个特定组织下的分支。通常这类包是为了满足特定项目(如 Tailwind CSS 等)的依赖需求而存在。如果它不是直接由原库作者维护,长期来看可能存在同步滞后风险。除非你有特定需求,否则通用项目应优先考虑主分支。
| 特性 | lru-cache | quick-lru | @alloc/quick-lru |
|---|---|---|---|
| 核心策略 | LRU (可配置) | LRU | LRU |
| 内置 TTL | ✅ 支持 | ❌ 不支持 | ❌ 不支持 |
| 异步获取 | ✅ 支持 (fetchMethod) | ❌ 不支持 | ❌ 不支持 |
| 脏读 (Stale) | ✅ 支持 (allowStale) | ❌ 不支持 | ❌ 不支持 |
| 大小限制 | 条目数 或 字节大小 | 仅条目数 | 仅条目数 |
| API 复杂度 | 高 (功能多) | 低 (极简) | 低 (极简) |
| 典型场景 | 服务端缓存、复杂数据 | 前端工具、配置缓存 | 特定工具链依赖 |
lru-cache 是功能最全面的解决方案。如果你的应用运行在 Node.js 服务端,并且需要处理复杂的缓存失效逻辑、异步数据加载或对内存占用有精确控制(通过 sizeCalculation),它是唯一的选择。它的学习曲线稍陡,但能解决绝大多数生产级问题。
quick-lru 是前端和轻量级工具的最佳伙伴。如果你在浏览器中运行,或者只是需要缓存一些计算结果、配置项,不需要时间过期,它的简单性是巨大的优势。更少的代码意味着更少的潜在 Bug。
@alloc/quick-lru 通常出现在特定依赖树中。除非你正在维护一个明确依赖此包的工具链,或者需要该分支提供的特定修复,否则在新项目中,建议直接使用 quick-lru 以获得更广泛的社区支持和更清晰的维护路径。
最终建议:对于大多数现代 Web 应用,lru-cache 提供了最好的长期保障,而 quick-lru 在追求极致轻量的场景下依然有一席之地。避免使用不再维护的分支版本,除非有明确的必要性。
如果你的项目需要企业级的稳定性、复杂的缓存失效策略(如 TTL、最大年龄)或异步支持,请选择 lru-cache。它是行业标准,文档完善,适合处理高并发或复杂状态管理的场景,尽管它的体积相对较大。
仅在你是为了兼容特定依赖树(如某些构建工具的内部依赖)或需要该分支特有的修复时才选择 @alloc/quick-lru。对于全新的通用项目,通常建议直接使用 quick-lru 或 lru-cache,除非你有明确的理由需要使用这个特定命名空间的版本。
如果你只需要一个简单的内存缓存,且对包体积敏感,或者在浏览器端运行,quick-lru 是更好的选择。它的 API 直观,没有多余的依赖,适合缓存配置、简单计算结果等轻量级场景。
A cache object that deletes the least-recently-used items.
Specify a max number of the most recently used items that you want to keep, and this cache will keep that many of the most recently accessed items.
This is not primarily a TTL cache, and does not make strong TTL
guarantees. There is no preemptive pruning of expired items by
default, but you may set a TTL on the cache or on a single
set. If you do so, it will treat expired items as missing, and
delete them when fetched. If you are more interested in TTL
caching than LRU caching, check out
@isaacs/ttlcache.
As of version 7, this is one of the most performant LRU implementations available in JavaScript, and supports a wide diversity of use cases. However, note that using some of the features will necessarily impact performance, by causing the cache to have to do more work. See the "Performance" section below.
npm install lru-cache --save
// hybrid module, either works
import { LRUCache } from 'lru-cache'
// or:
const { LRUCache } = require('lru-cache')
// or in minified form for web browsers:
import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs'
// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent
// unsafe unbounded storage.
//
// In most cases, it's best to specify a max for performance, so all
// the required memory allocation is done up-front.
//
// All the other options are optional, see the sections below for
// documentation on what each one does. Most of them can be
// overridden for specific items in get()/set()
const options = {
max: 500,
// for use with tracking overall storage size
maxSize: 5000,
sizeCalculation: (value, key) => {
return 1
},
// for use when you need to clean up something when objects
// are evicted from the cache
dispose: (value, key, reason) => {
freeFromMemoryOrWhatever(value)
},
// for use when you need to know that an item is being inserted
// note that this does NOT allow you to prevent the insertion,
// it just allows you to know about it.
onInsert: (value, key, reason) => {
logInsertionOrWhatever(key, value)
},
// how long to live in ms
ttl: 1000 * 60 * 5,
// return stale items before removing from cache?
allowStale: false,
updateAgeOnGet: false,
updateAgeOnHas: false,
// async method to use for cache.fetch(), for
// stale-while-revalidate type of behavior
fetchMethod: async (key, staleValue, { options, signal, context }) => {},
}
const cache = new LRUCache(options)
cache.set('key', 'value')
cache.get('key') // "value"
// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)
cache.clear() // empty the cache
If you put more stuff in the cache, then less recently used items will fall out. That's what an LRU cache is.
For full description of the API and all options, please see the LRUCache typedocs
This implementation aims to be as flexible as possible, within the limits of safe memory consumption and optimal performance.
At initial object creation, storage is allocated for max items.
If max is set to zero, then some performance is lost, and item
count is unbounded. Either maxSize or ttl must be set if
max is not specified.
If maxSize is set, then this creates a safe limit on the
maximum storage consumed, but without the performance benefits of
pre-allocation. When maxSize is set, every item must provide
a size, either via the sizeCalculation method provided to the
constructor, or via a size or sizeCalculation option provided
to cache.set(). The size of every item must be a positive
integer.
If neither max nor maxSize are set, then ttl tracking must
be enabled. Note that, even when tracking item ttl, items are
not preemptively deleted when they become stale, unless
ttlAutopurge is enabled. Instead, they are only purged the
next time the key is requested. Thus, if ttlAutopurge, max,
and maxSize are all not set, then the cache will potentially
grow unbounded.
In this case, a warning is printed to standard error. Future
versions may require the use of ttlAutopurge if max and
maxSize are not specified.
If you truly wish to use a cache that is bound only by TTL
expiration, consider using a Map object, and calling
setTimeout to delete entries when they expire. It will perform
much better than an LRU cache.
Here is an implementation you may use, under the same license as this package:
// a storage-unbounded ttl cache that is not an lru-cache
const cache = {
data: new Map(),
timers: new Map(),
set: (k, v, ttl) => {
if (cache.timers.has(k)) {
clearTimeout(cache.timers.get(k))
}
cache.timers.set(
k,
setTimeout(() => cache.delete(k), ttl),
)
cache.data.set(k, v)
},
get: k => cache.data.get(k),
has: k => cache.data.has(k),
delete: k => {
if (cache.timers.has(k)) {
clearTimeout(cache.timers.get(k))
}
cache.timers.delete(k)
return cache.data.delete(k)
},
clear: () => {
cache.data.clear()
for (const v of cache.timers.values()) {
clearTimeout(v)
}
cache.timers.clear()
},
}
If that isn't to your liking, check out @isaacs/ttlcache.
This cache never stores undefined values, as undefined is used
internally in a few places to indicate that a key is not in the
cache.
You may call cache.set(key, undefined), but this is just
an alias for cache.delete(key). Note that this has the effect
that cache.has(key) will return false after setting it to
undefined.
cache.set(myKey, undefined)
cache.has(myKey) // false!
If you need to track undefined values, and still note that the
key is in the cache, an easy workaround is to use a sigil object
of your own.
import { LRUCache } from 'lru-cache'
const undefinedValue = Symbol('undefined')
const cache = new LRUCache(...)
const mySet = (key, value) =>
cache.set(key, value === undefined ? undefinedValue : value)
const myGet = (key, value) => {
const v = cache.get(key)
return v === undefinedValue ? undefined : v
}
Most methods can accept a status option, which is an
LRUCache.Status
object that will be decorated along the operation with
indications about what was done and why.
Additionally, this library is instrumented using the
node:diagnostics_channel
module on Node and other platforms that support it. In order to
get diagnostics metrics, listen on the
channel('lru-cache:metrics'). To get Tracing Channel traces,
subscribe to the tracingChannel('lru-cache'). The
LRUCache.Status
objects will be provided as the message context to those channel
listeners.
For example, you could do the following to get comprehensive information about every LRUCache instance in your application:
import { tracingChannel, subscribe } from 'node:diagnostics_channel'
subscribe('lru-cache:metrics', (message, name) => {
// name will always be 'lru-cache:metrics'
// message will be the LRUCache.Status object for whatever
// synchronous operation was performed.
console.error('LRUCache Metrics', message)
})
tracingChannel('lru-cache').subscribe({
start: status => {
// a traced operation is starting
},
asyncStart: status => {
// an async traced operation is starting
},
asyncEnd: status => {
// an async traced operation is ending
}
error: status => {
// a traced operation failed
},
end: status => {
// a traced operation is complete
},
})
The async cache.fetch() and cache.forceFetch methods are
covered by tracingChannels. All the other operations are
covered by the lru-cache:metrics channel, because they are
strictly synchronous, and thus don't have an asynchronous
lifecycle to track.
Note that using status objects or using
node:diagnostics_channel listeners will impose a modest
performance penalty. Creating data objects is not ever free; do
not believe anyone who tells you otherwise. But it is as small as
possible.
Not all platforms support the node:diagnostics_channel module.
Currently, this is only available in Node, Bun, and Deno, and
some edge computing platforms that provide a Node compatibility
layer.
To work around this, if you are loading in a non-Node
environment, the package.json exports will direct your module
loader to pull in a version that starts out with a dummy
implementation, then does a conditional dynamic import of the
node:diagnostics_channel module, and then swaps out those
dummy objects with the real thing if it succeeds. This means that
cache metrics and tracing channels started in the first load-time
tick of your application will not be covered, except in
environments that load using the require import
condition, or both the node and esm import conditions
together.
Top-level await could be used to remove this caveat, but that feature is dead on arrival, unfortunately. See #397 and #398 for more details.
As of April 2026, version 11 of this library is one of the most performant LRU cache implementations in JavaScript.
Benchmarks can be extremely difficult to get right. In particular, the performance of set/get/delete operations on objects will vary wildly depending on the type of key used. V8 is highly optimized for objects with keys that are short strings, especially integer numeric strings. Thus any benchmark which tests solely using numbers as keys will tend to find that an object-based approach performs the best.
Note that coercing anything to strings to use as object keys is unsafe, unless you can be 100% certain that no other type of value will be used. For example:
const myCache = {}
const set = (k, v) => (myCache[k] = v)
const get = k => myCache[k]
set({}, 'please hang onto this for me')
set('[object Object]', 'oopsie')
Also beware of "Just So" stories regarding performance. Garbage collection of large (especially: deep) object graphs can be incredibly costly, with several "tipping points" where it increases exponentially. As a result, putting that off until later can make it much worse, and less predictable. If a library performs well, but only in a scenario where the object graph is kept shallow, then that won't help you if you are using large objects as keys.
In general, when attempting to use a library to improve performance (such as a cache like this one), it's best to choose an option that will perform well in the sorts of scenarios where you'll actually use it.
This library is optimized for repeated gets and minimizing eviction time, since that is the expected need of a LRU. Set operations are somewhat slower on average than a few other options, in part because of that optimization. It is assumed that you'll be caching some costly operation, ideally as rarely as possible, so optimizing set over get would be unwise.
If performance matters to you:
If it's at all possible to use small integer values as keys, and you can guarantee that no other types of values will be used as keys, then do that, and use a cache such as lru-fast, or mnemonist's LRUCache which uses an Object as its data store.
Failing that, if you can use short non-numeric strings (ie, less than 256 characters) as your keys, and you do not need any of the other features of this library, use mnemonist's LRUCache.
If the types of your keys will be anything else, especially long strings, strings that look like floats, objects, or some mix of types, or if you aren't sure, then this library will work well for you.
If you do not need the features that this library provides (like asynchronous fetching, a variety of TTL staleness options, and so on), then mnemonist's LRUMap is also a very good option, and just slightly faster than this module (since it does considerably less).
Do not use a dispose function, size tracking, or especially
ttl behavior or observability features, unless absolutely
needed. These features are convenient, and necessary in some
use cases, and every attempt has been made to make the
performance impact minimal, but it isn't nothing.
When writing tests that involve TTL-related functionality, note
that this module creates an internal reference to the global
performance or Date objects at import time. If you import it
statically at the top level, those references cannot be mocked or
overridden in your test environment.
To avoid this, dynamically import the package within your tests so that the references are captured after your mocks are applied. For example:
// ❌ Not recommended
import { LRUCache } from 'lru-cache'
// mocking timers, e.g. jest.useFakeTimers()
// ✅ Recommended for TTL tests
// mocking timers, e.g. jest.useFakeTimers()
const { LRUCache } = await import('lru-cache')
This ensures that your mocked timers or time sources are respected when testing TTL behavior.
Additionally, you can pass in a perf option when creating your
LRUCache instance. This option accepts any object with a now
method that returns a number.
For example, this would be a very bare-bones time-mocking system you could use in your tests, without any particular test framework:
import { LRUCache } from 'lru-cache'
let myClockTime = 0
const cache = new LRUCache<string>({
max: 10,
ttl: 1000,
perf: {
now: () => myClockTime,
},
})
// run tests, updating myClockTime as needed
This library changed to a different algorithm and internal data structure in version 7, yielding significantly better performance, albeit with some subtle changes as a result.
If you were relying on the internals of LRUCache in version 6 or before, it probably will not work in version 7 and above.
fetchContext option was renamed to context, and may no
longer be set on the cache instance itself.null or undefined.'lru-cache/min', for both CJS
and MJS builds.cache.fetch() return type is now Promise<V | undefined>
instead of Promise<V | void>. This is an irrelevant change
practically speaking, but can require changes for TypeScript
users.For more info, see the change log.