Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS memory consumption in an infinite loop

I don't know if this is a bug with Node or V8, but if I run the following code the node process leaks memory. The GC never seems to kick in and in a few seconds it's consuming >1GB of memory. This is unexpected behavior. Am I missing something?

Here's the code:

for(;;) { console.log(1+1); }

Obviously, this is a little bit of a contrived situation, but I can see an issue with a long-running process that would never free memory.

Edit: I tried both with v0.5.10 (unstable) and v0.4.12 (stable) and the unstable version performs a little bit better---the stable version just stops outputting to the console but continues to consume memory, whereas the stable version continues executing and consuming memory without pause.

like image 496
Matty Avatar asked Oct 26 '11 10:10

Matty


1 Answers

You are blocking node.js event loop by never returning to it.

When you write something to a stream node.js does that asynchronously: it sends the write request, queues information about sent request in the stream's internal data-structures and awaits the callback that would notify it about the completion.

If you are blocking event loop the callback will never be called (because incoming events are never processed) and auxiliary data structures queued in the stream will never be freed.

The same can probably happen if you "overload" event loop by constantly scheduling your own events with nextTick/setInterval/setTimeout.

like image 145
Vyacheslav Egorov Avatar answered Oct 15 '22 07:10

Vyacheslav Egorov