4

This simple code makes app crash with out of memory:

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())

So how properly recycle the buffer so it can be reused? Not sure if clear or delete are appropriate methods but how then? Thank you

John Glabb
  • 1,336
  • 5
  • 22
  • 52

1 Answers1

5

As mentioned in one of the answers, the buffer does not have a clear() method to un-allocate/free the allocated buffer memory. You can request the Node's gc to free-up the unused memory by calling gc() method but that option is only available when your application is started with --expose-gc flag.

'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());

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

Sanket
  • 945
  • 11
  • 24