v0.10.4
Here's the simple loop that results in an ever-increasing memory usage:
function redx(){
setTimeout(function(){ redx() },1000);
console.log('loop');
}
redx();
What am I doing wrong ??
OK, just tried the suggestion to reference the timeout object in the scope and it seems that garbage collection does kick in after about 40 seconds, here's abbreviated logs from TOP:
3941 root 20 0 32944 7284 4084 S 4.587 3.406 0:01.32 node
3941 root 20 0 32944 7460 4084 S 2.948 3.489 0:01.59 node
3941 root 20 0 32944 7516 4084 S 2.948 3.515 0:01.68 node
3941 root 20 0 33968 8400 4112 S 2.948 3.928 0:02.15 node
3941 root 20 0 33968 8920 4112 S 3.275 4.171 0:02.98 node
3941 root 20 0 33968 8964 4112 S 2.948 4.192 0:03.07 node
3941 root 20 0 33968 9212 4112 S 2.953 4.308 0:03.16 node
3941 root 20 0 33968 9212 4112 S 2.953 4.308 0:03.25 node
3941 root 20 0 33968 9212 4112 S 3.276 4.308 0:03.35 node
3941 root 20 0 33968 9212 4112 S 2.950 4.308 0:03.44 node
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();
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 );
}

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