← 中文资源

简体中文版本

WeakMap 按对象身份做记忆化

WeakMap 的键只能是对象:以请求选项对象为键缓存规范化结果,第二次取回的是同一实例;对象被回收时缓存条目跟着消失,不会内存泄漏。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

fast: {"url":"/api/items","retries":0,"timeoutMs":2000}
flaky: {"url":"/api/upload","retries":3,"timeoutMs":17000}
memo hit is identical: true
distinct keys stay distinct: false

实现说明

逻辑集中在函数 normalize里。

使用要点

  • 守卫 cached 满足时靠提前的 return 短路流程。
  • 每一步打印都带着自己的标签:fast:、flaky:、memo hit is identical:。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 normalize。

主签名形如 function normalize(options: RequestOptions)

核心语句

if (cached) return cached;

代码示例

// WeakMap<K extends object, V> memoizes per object identity, and only
// objects can ever become keys.
interface RequestOptions {
  readonly url: string;
  readonly retries: number;
}

interface NormalizedOptions {
  url: string;
  retries: number;
  timeoutMs: number;
}

const normalized = new WeakMap<RequestOptions, NormalizedOptions>();

function normalize(options: RequestOptions): NormalizedOptions {
  const cached = normalized.get(options);
  if (cached) return cached;
  const value: NormalizedOptions = {
    url: options.url,
    retries: options.retries,
    timeoutMs: options.retries * 5000 + 2000,
  };
  normalized.set(options, value);
  return value;
}

const fast: RequestOptions = { url: '/api/items', retries: 0 };
const flaky: RequestOptions = { url: '/api/upload', retries: 3 };

console.log('fast:', JSON.stringify(normalize(fast)));
console.log('flaky:', JSON.stringify(normalize(flaky)));

// The second call for the same object returns the identical instance
console.log('memo hit is identical:', normalize(fast) === normalize(fast));
console.log('distinct keys stay distinct:', normalize(fast) === normalize(flaky));