实现说明
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');