NodeJS memory consumption in an infinite loop

前端 未结 3 903
我在风中等你
我在风中等你 2021-02-05 12:35

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

相关标签:
3条回答
  • 2021-02-05 12:55

    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.

    0 讨论(0)
  • 2021-02-05 12:58

    As Node.js v0.10 has been released, setImmediate should be used as the first choice instead of process.nextTick when calling the recursive callback.

    function loginf() {
      console.log(1+1);
      setImmediate(loginf);
    }
    loginf();
    

    The memory consumption of this chunk of code kept low ( <10MB ) after running for about 15 mins on my computer.

    On the contrary, Running the infinite for loop caused memory leek and the process.nextTick throwed an Maximum call stack size exceeded error.

    Check this Q&A also: setImmediate vs. nextTick

    0 讨论(0)
  • 2021-02-05 13:09

    The answer by @VyacheslavEgorov seems right on but I would guess that deferring to the event loop would solve the problem. You might want to compare how your infinite for-loop compares to this infinite looping strategy:

    function loginf() {
      console.log(1+1);
      process.nextTick(loginf);
    }
    loginf();
    

    The idea is to use process.nextTick(cb) to defer to the event loop and (presumably) allow the GC to do its thing.

    0 讨论(0)
提交回复
热议问题