nodejs setTimeout memory leak?

后端 未结 2 1811
有刺的猬
有刺的猬 2021-02-04 13:07

v0.10.4

Here\'s the simple loop that results in an ever-increasing memory usage:

function redx(){
      setTimeout(function(){ redx() },1000);
      cons         


        
相关标签:
2条回答
  • 2021-02-04 13:18

    Actually, I think it might be just the way the V8 garbage collector works.

    On my system, node heap tends to increase up to 48 MB and then stabilize, so I think if you keep your program running for a long time, the memory consumption will eventually stabilize.

    You can have information about when/how the GC kicks in by launching node with one of the V8 command line option: the --trace_gc flag.

    In your first tries with Redis, you were systematically connecting/disconnecting from Redis at each call. This tends to generate garbage. You are supposed to open a connection once and use it many times. Nevertheless, even when I do this, memory consumption tends to stabilize. Here is the evolution of memory consumption on this example with Redis:

    // something close to your initial function (when Redis was still in the picture)
    function redx(){
        var client = redis.createClient();
        client.get("tally", function(err, reply) {
            client.quit();
        });
        setTimeout(function(){ redx() }, 50 );
    }
    

    Evolution of memory consumption with Redis connect/disconnect

    Here, the stabilization after 60 MB seems to be quite obvious.

    0 讨论(0)
  • 2021-02-04 13:23

    No idea why but apparently if you reference the timeout object in the scope of the function nodejs will do the garbage collect that correctly.

    function redx(){
          var t = setTimeout(function(){ redx() },50);
          console.log('hi');
    }
    
    redx();
    
    0 讨论(0)
提交回复
热议问题