lru-caching
v1.1.0
Published
A high-performance LRU caching implementation with TTL support, batch operations and memory optimization
Downloads
10
Maintainers
Readme
lru-caching
高性能的LRU(最近最少使用)缓存实现,适用于Node.js和浏览器环境,支持TTL过期策略、批量操作、内存优化和详细统计功能。
特性
- 高性能:使用基于数组的节点而非对象,访问速度更快
- LRU + TTL:同时支持最近最少使用淘汰策略和生存时间过期机制
- 批量操作:高效处理多个条目,支持批量添加和删除
- 内存优化:节点池机制减少垃圾回收开销
- 统计功能:跟踪命中率、淘汰数和过期数等指标
- 类型安全:完整的TypeScript支持,包含类型定义
- 资源管理:可选的淘汰回调函数,用于清理资源
安装
npm install lru-caching
# 或
yarn add lru-caching基本用法
import LRU from 'lru-caching';
// 创建一个最大容量为100条目的LRU缓存
const cache = new LRU<string>(100);
// 添加条目
cache.put('key1', 'value1');
cache.put('key2', 'value2', 5000); // 5秒后过期(TTL)
// 获取条目
console.log(cache.get('key1')); // 'value1'
// 检查存在性
console.log(cache.has('key2')); // true
// 删除条目
cache.delete('key1');
// 获取缓存大小
console.log(cache.len()); // 1高级用法
批量操作
// 批量添加条目
const evicted = cache.batchPut([
{ key: 'a', value: 'alpha' },
{ key: 'b', value: 'beta', ttl: 10000 },
{ key: 'c', value: 'gamma' }
]);
// 批量删除条目
const deleted = cache.batchDelete(['a', 'b']);TTL(生存时间)
// 添加2秒后过期的条目
cache.put('temp', 'data', 2000);
// 条目存在
console.log(cache.get('temp')); // 'data'
// 等待3秒
setTimeout(() => {
// 条目已过期
console.log(cache.get('temp')); // undefined
}, 3000);统计信息
// 每秒打印一次缓存统计信息
setInterval(() => {
const stats = cache.getStats();
console.log(`
命中次数: ${stats.get.hit},
未命中次数: ${stats.get.total - stats.get.hit},
命中率: ${stats.get.hitRate}%,
淘汰次数: ${stats.put.evict},
过期次数: ${stats.put.expire}
`);
}, 1000);资源清理
// 带有淘汰回调的缓存,用于资源清理
const resourceCache = new LRU<WebGLTexture>(5, 0.5, 30000, 5000, (key, texture) => {
// 当纹理被淘汰时清理WebGL纹理
const gl = getWebGLContext();
gl.deleteTexture(texture);
});
// 向缓存添加WebGL纹理
const texture = gl.createTexture();
resourceCache.put('texture1', texture);API
构造函数
new LRU<T>(
maxSize: number,
initialPoolRatio = 0.5,
poolAdjustInterval = 30000,
expireCheckInterval = 5000,
onEvict?: (key: string | number, value: T) => void
)maxSize:缓存可容纳的最大条目数initialPoolRatio:节点池初始大小与maxSize的比例(默认:0.5)poolAdjustInterval:动态调整节点池大小的间隔(毫秒,默认:30000)expireCheckInterval:检查过期条目的间隔(毫秒,默认:5000)onEvict:条目被淘汰时的回调函数(用于资源清理)
方法
put(key: string | number, value: T, ttl?: number): T | null
向缓存添加或更新条目。如果缓存已满,返回被淘汰的值。
key:条目键value:条目值ttl:生存时间(毫秒,可选)
get(key: string | number): T | undefined
从缓存获取条目。如果未找到或已过期,返回undefined。
key:条目键
delete(key: string | number): T | null
从缓存删除条目。返回被删除的值或null。
key:条目键
batchPut(entries: Array<{ key: string | number; value: T; ttl?: number }>): T[]
批量添加多个条目。返回被淘汰的值数组。
batchDelete(keys: (string | number)[]): T[]
批量删除多个条目。返回被删除的值数组。
has(key: string | number): boolean
检查条目是否存在且未过期。
len(): number
获取缓存中当前的条目数量。
forEach(cb: (key: string | number, value: T, expireTime?: number) => void): void
遍历缓存中的所有条目。
getStats(): Readonly<Stats>
获取缓存统计信息:
get.total:总获取操作次数get.hit:成功获取次数get.hitRate:命中率百分比put.total:总添加操作次数put.evict:被淘汰的条目数put.expire:已过期的条目数pool.size:当前节点池大小pool.maxSize:节点池最大容量
clear(): void
清空缓存中的所有条目。
dispose(): void
清理缓存资源(停止定时器,有助于垃圾回收)。
性能优化
- 基于数组的节点:使用数组而非对象存储缓存条目,减少属性访问开销
- 节点池:重用被淘汰的节点,减少垃圾回收
- 自适应池大小:根据使用模式动态调整节点池大小
- 批量处理:高效处理多个操作,减少开销
- 延迟统计:批量更新统计信息,减少性能影响
许可证
MIT
