如何在 JavaScript 中正确回收缓冲区

How to properly recycle a buffer in JavaScript

这个简单的代码使应用程序因内存不足而崩溃:

var buf;
console.log(process.memoryUsage())
for(i=0; i<10000000; i++){
    buf = Buffer.alloc(1024)
    buf.clear
    delete buf
    buf = null
}
console.log(process.memoryUsage())

那么如何正确回收缓冲区以便重复使用呢? 不确定 clear 或 delete 是否是合适的方法,但是如何呢? 谢谢

如其中一个答案所述,缓冲区没有 clear() 方法来 un-allocate/free 分配的缓冲区内存。您可以通过调用 gc() 方法请求 节点的 gc 释放未使用的内存,但该选项仅在您的应用程序以 --expose- 启动时可用gc 标志。

'use strict';
let buf;
console.log(process.memoryUsage());
for (let i = 0; i < 10000000; i++) {

    buf = Buffer.alloc(1024);
    // Do your stuff
}

if (global.gc) {
    console.log('Requesting gc to free-up unsed memory');
    global.gc(); // Synchronous call, may take longer time and further execution get blocked till it finishes the execution
}

console.log(process.memoryUsage());

链接:How to request the Garbage Collector in node.js to run?