Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

At startup, it seems my node.js app uses around 200MB of memory. If I leave it alone for a while, it shrinks to around 9MB.

Is it possible from within the app to:

  1. Check how much memory the app is using ?
  2. Request the garbage collector to run ?

The reason I ask is, I load a number of files from disk, which are processed temporarily. This probably causes the memory usage to spike. But I don't want to load more files until the GC runs, otherwise there is the risk that I will run out of memory.

Any suggestions ?

like image 609
Rahul Iyer Avatar asked Dec 05 '14 18:12

Rahul Iyer


People also ask

When you request garbage collector to run it will start to run immediately?

It is not possible to run garbage collection immediately as we are programming in managed environment and only CLR decides when to run garbage collection.

Does Nodejs have a garbage collector?

Luckily for you, Node. js comes with a garbage collector, and you don't need to manually manage memory allocation.

How do I force garbage collection in JavaScript?

You can't force garbage collection (not in any sane fashion). If your variables aren't going out of scope automatically, just set them to null . Show activity on this post. Best advice is to define them in scope that makes them eligible for garbage collection.


1 Answers

If you launch the node process with the --expose-gc flag, you can then call global.gc() to force node to run garbage collection. Keep in mind that all other execution within your node app is paused until GC completes, so don't use it too often or it will affect performance.

You might want to include a check when making GC calls from within your code so things don't go bad if node was run without the flag:

try {   if (global.gc) {global.gc();} } catch (e) {   console.log("`node --expose-gc index.js`");   process.exit(); } 
like image 132
IgnisFatuus Avatar answered Sep 23 '22 01:09

IgnisFatuus