Robert Eisele
Systems Engineer, Architect and DBA

Forcing Garbage Collection in node.js and JavaScript

If you have a quite complex project which allocates lots of memory and drops it away quickly, the garbage collector of node.js or better V8 has to tidy up the memory. It became better since the first versions of node, but cleaning large chunks of memory can pause the application for a while. Forcing the GC manually when your application has time for it can make sense.

While R has a global function gc() and Java comes with System.gc(), JavaScript is missing a function like that. At least in the normal mode. You can start node with a flag:

$ node --expose-gc file.js

When you start node with this option, you get a function exposed like this:

global.gc();

In order to make it safer, you can use:

function forceGC()
   if (global.gc) {
      global.gc();
   } else {
      console.warn('No GC hook! Start your program as `node --expose-gc file.js`.');
   }
}

You might also be interested in the following

Leave a comment

8 - 6