这四个库都是用于 Node.js 环境下的进程内缓存方案,旨在通过内存存储键值对来提升应用性能。lru-cache 是目前最主流的选择,提供高性能的最近最少使用(LRU)淘汰策略。node-cache 功能丰富,支持事件监听和数据克隆。quick-lru 主打极简主义,依赖少且体积小。memory-cache 曾是流行选择,但近年来维护频率较低。它们都适用于接口响应缓存、计算结果暂存等场景,但在 API 设计、过期策略和维护状态上存在显著差异。
在 Node.js 服务端开发中,进程内缓存(In-Memory Cache)是减少数据库压力、加速响应的重要手段。lru-cache、node-cache、quick-lru 和 memory-cache 都是这一领域的常见选择,但它们的设计理念和适用场景各不相同。本文将从初始化、数据操作、过期策略、安全性及维护状态五个维度进行深度对比。
配置方式决定了缓存的灵活性和上手难度。不同的库对最大容量和默认过期时间的处理有所不同。
lru-cache 采用明确的配置对象,支持最大条目数、最大内存大小等多种限制。
const { LRUCache } = require('lru-cache');
const cache = new LRUCache({
max: 500, // 最大条目数
ttl: 1000 * 60, // 默认过期时间 (毫秒)
maxSize: 1000000 // 最大内存占用 (字节)
});
node-cache 配置项非常直观,支持设置标准过期时间和检查周期。
const NodeCache = require('node-cache');
const cache = new NodeCache({
stdTTL: 100, // 默认过期时间 (秒)
checkperiod: 120 // 检查过期键的周期 (秒)
});
quick-lru 配置极简,主要关注最大尺寸,不支持复杂的内存限制。
const QuickLRU = require('quick-lru');
const cache = new QuickLRU({
maxSize: 1000 // 仅支持最大条目数
});
memory-cache 初始化最简单,通常不需要配置即可直接使用,适合快速原型。
const Cache = require('memory-cache');
const cache = new Cache();
// 无构造函数配置,所有选项在写入时指定
API 的一致性影响代码的可读性和迁移成本。注意 memory-cache 使用了不同的写入方法名。
lru-cache 使用标准的 set 和 get 方法,符合现代 JavaScript 习惯。
// 写入
cache.set('userId', 123);
// 读取
const id = cache.get('userId');
node-cache 同样使用 set 和 get,但 set 支持链式调用。
// 写入 (返回 this 支持链式)
cache.set('userId', 123);
// 读取
const id = cache.get('userId');
quick-lru 遵循标准的 set 和 get 接口,非常简单。
// 写入
cache.set('userId', 123);
// 读取
const id = cache.get('userId');
memory-cache 使用 put 方法写入,这与大多数现代库不同,需要注意区分。
// 写入 (注意是 put 而不是 set)
cache.put('userId', 123);
// 读取
const id = cache.get('userId');
过期策略是缓存库的核心功能之一。quick-lru 在此方面有明显限制。
lru-cache 支持在写入时单独指定 TTL,优先级高于默认值。
// 单独指定过期时间 (毫秒)
cache.set('session', 'abc', { ttl: 1000 * 60 });
node-cache 在 set 方法的第三个参数直接传入秒数。
// 单独指定过期时间 (秒)
cache.set('session', 'abc', 60);
quick-lru 不支持原生 TTL。它仅基于大小进行淘汰,如果需要过期功能,需自行实现包装逻辑。
// 不支持 TTL 参数
cache.set('session', 'abc');
// 需自行管理过期时间或使用其他库
memory-cache 在 put 方法的第三个参数传入毫秒数。
// 单独指定过期时间 (毫秒)
cache.put('session', 'abc', 60000);
在多线程或复杂引用场景下,直接返回对象引用可能导致意外修改。node-cache 在此处表现独特。
lru-cache 默认直接返回引用,性能最高,但修改缓存值会影响内部状态。
const user = cache.get('user');
user.name = 'New Name'; // 直接修改了缓存中的对象
node-cache 默认克隆返回的值,防止外部修改影响缓存数据,但会有性能开销。
const user = cache.get('user');
user.name = 'New Name'; // 缓存内部数据不受影响 (默认开启 clone)
quick-lru 直接返回引用,设计目标是极简和速度。
const user = cache.get('user');
user.name = 'New Name'; // 直接修改了缓存中的对象
memory-cache 直接返回引用,无自动克隆保护。
const user = cache.get('user');
user.name = 'New Name'; // 直接修改了缓存中的对象
选择开源库时,维护活跃度直接关系到生产环境的稳定性。
lru-cache 由 npm 创始人维护,更新频繁,是事实上的行业标准。类型定义完善,适合 TypeScript 项目。
node-cache 维护状态良好,社区稳定,适合需要特定功能(如事件)的场景。
quick-lru 由 Sindre Sorhus 维护,质量可靠,但功能更新较少,定位明确为极简场景。
memory-cache 近年来更新频率显著降低,社区讨论减少。虽然目前可用,但在新架构中引入可能存在长期维护风险。
| 特性 | lru-cache | node-cache | quick-lru | memory-cache |
|---|---|---|---|---|
| 写入方法 | set | set | set | put |
| TTL 支持 | ✅ (毫秒) | ✅ (秒) | ❌ 不支持 | ✅ (毫秒) |
| 数据克隆 | ❌ 默认引用 | ✅ 默认克隆 | ❌ 默认引用 | ❌ 默认引用 |
| 事件系统 | ❌ 无 | ✅ 支持 | ❌ 无 | ❌ 无 |
| 维护状态 | 🟢 非常活跃 | 🟢 活跃 | 🟢 稳定 | 🟡 低频 |
| 主要优势 | 性能与标准 | 功能丰富 | 极简依赖 | 简单上手 |
lru-cache 是目前最稳妥的选择 — 它兼顾了性能、功能和维护性,适合绝大多数生产环境。如果你的项目对内存敏感或需要精细控制,它是首选。
node-cache 适合需要监听缓存事件或担心对象引用污染的场景 — 它的默认克隆机制虽然消耗性能,但能减少很多潜在的 Bug。
quick-lru 适合嵌入式场景或极简工具 — 当你只需要一个按大小淘汰的映射表,且不需要过期功能时,它是最轻量的。
memory-cache 建议逐步淘汰 — 除非是为了维护旧代码,否则新项目应避免使用,转而投向更活跃的 lru-cache 生态。
最终结论:在现代 Node.js 架构中,优先使用 lru-cache。只有在明确需要 node-cache 的事件系统或克隆特性时,才考虑替代方案。避免使用 quick-lru 处理需要过期的数据,也不要在新项目中依赖 memory-cache。
选择 lru-cache 如果你需要目前社区最活跃、性能最优的标准解决方案。它在 v7 版本后重构了 API,支持更精细的内存控制和 TTL 设置,适合大多数高性能 Node.js 服务。
选择 memory-cache 仅为了维护旧项目兼容,新项目中不建议使用。虽然 API 简单,但相比 lru-cache 其维护频率较低,长期来看存在技术债务风险,建议迁移至更活跃的库。
选择 node-cache 如果你需要内置的事件系统(如 set/delete 事件)或默认的数据克隆功能以防止引用污染。它的 API 设计直观,适合需要监听缓存变化的复杂场景。
选择 quick-lru 如果你追求极致的简单性和最小的依赖体积,且不需要复杂的过期策略。它严格遵循 LRU 算法,适合对内存大小敏感且逻辑简单的工具库或小型服务。
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.