← 中文资源

简体中文版本

process.memoryUsage 测量堆前后变化

在工作负载前后各取一次 process.memoryUsage:rss 是进程驻留内存、heapUsed 才是对象图;分配 50 个 1MB Buffer 观察 heapUsed 上涨,释放引用后 GC 何时回收不承诺实时。

阅读英文原文

运行结果

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

before: rss 48.9 MB, heapUsed 4.0 MB, heapTotal 6.2 MB
allocated: 50 chunks x 1 MB
during: rss 98.8 MB, heapUsed 4.6 MB, heapTotal 6.4 MB
heap delta: + 0.6 MB
after (GC may lag until the next collection): rss 98.8 MB, heapUsed 4.6 MB, heapTotal 6.4 MB
rss never measures the object graph directly — heapUsed does

实现说明

process.memoryUsage 测量堆前后变化可以归结为函数 mb、snapshot。 本示例的循环部分是 for (let i = 0; i < 50; i++)。

使用要点

  • 每一步打印都带着自己的标签:allocated:、heap delta: +。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件在加载时定义 mb、snapshot。

签名一览:const mb = (n)

核心语句

const mb = (n) => `${(n / 1024 / 1024).toFixed(1)} MB`;

代码示例

function snapshot(label) {
  const m = process.memoryUsage();
  const mb = (n) => `${(n / 1024 / 1024).toFixed(1)} MB`;
  console.log(`${label}: rss ${mb(m.rss)}, heapUsed ${mb(m.heapUsed)}, heapTotal ${mb(m.heapTotal)}`);
  return m;
}

const before = snapshot('before');

// A bounded workload: buffers are allocated then explicitly dropped.
const chunks = [];
for (let i = 0; i < 50; i++) {
  chunks.push(Buffer.alloc(1024 * 1024, i));
}
console.log('allocated:', chunks.length, 'chunks x 1 MB');

const during = snapshot('during');
console.log('heap delta: +', ((during.heapUsed - before.heapUsed) / 1024 / 1024).toFixed(1), 'MB');

chunks.length = 0; // release the references

const after = snapshot('after (GC may lag until the next collection)');
console.log('rss never measures the object graph directly — heapUsed does');