Skip to main content
On this page

@std/cache

Unstable

This @std package is experimental and its API may change without a major version bump.

Overview Jump to heading

In-memory cache utilities, such as memoization and caches with different expiration policies.

import { memoize, LruCache, type MemoizationCacheResult } from "@std/cache";
import { assertEquals } from "@std/assert";

const cache = new LruCache<string, MemoizationCacheResult<bigint>>(1000);

// fibonacci function, which is very slow for n > ~30 if not memoized
const fib = memoize((n: bigint): bigint => {
  return n <= 2n ? 1n : fib(n - 1n) + fib(n - 2n);
}, { cache });

assertEquals(fib(100n), 354224848179261915075n);

Add to your project Jump to heading

deno add jsr:@std/cache

See all symbols in @std/cache on

什么是缓存? Jump to heading

缓存将最近使用或计算成本高的数据存储在内存中,以便下次可以更快地重复使用,而不是重新计算或重新获取。当计算缓慢、网络调用频繁或反复访问相同数据时,缓存非常有用。

记忆化是函数结果的缓存:给定相同的输入,返回之前计算过的输出。它适用于纯函数(无副作用),结果仅取决于输入的情况。

为什么使用 @std/cache? Jump to heading

该包提供了一个现成的 memoize() 辅助函数和常见的缓存类型,这样你就不必自己构建它们。

该包兼容 Deno/Node/Bun/Workers 等环境,并保持 API 简洁且可预测。

LRU Jump to heading

LRU(最近最少使用)会驱逐你最长时间未使用的条目。适用于“近期的数据很可能会再次使用”的场景。适合热点工作集。

TTL Jump to heading

TTL(存活时间)在固定时间后驱逐条目,无论是否访问。适用于数据快速过期的情况(例如,来自服务的配置、短期有效的令牌)。

  • 根据工作负载选择驱逐策略:时间局部性用 LRU,数据新鲜度用 TTL,内存受限时用基于大小的策略。
  • 记忆化缓存必须考虑参数的标识性——对象/函数需要稳定的键(例如序列化或适当时用 WeakMap)。
  • 注意防止无限增长;设定合理限制并通过命中率调整容量。
  • 明确处理错误/超时——缓存仅成功结果,除非失败结果也应保留。

示例 Jump to heading

import { LruCache, memoize } from "@std/cache";

const cache = new LruCache<string, number>(500);
const fib = memoize(
  (n: number): number => n <= 1 ? n : fib(n - 1) + fib(n - 2),
  { cache },
);

你找到了你需要的东西吗?

编辑此页面
隐私政策