Search code examples
node.jsv8

Node.JS memory deallocation


I wrote a simple node server:

var http = require('http');

var server = http.createServer();

var i = 0;
var onRequest = function(req, res){
    res.write('test ' + (++i));
    res.end();
    console.log(i);
};

server.on('request', onRequest);

server.listen(8080);

When I started the server, node was using 5.8 MB of memory, But after serving 100,000 requests, it had memory usage of 21.5 MB.

Will this memory be deallocated at some point (when)?

I'm sure there's no memory leak in the script, it's too simple.

I'm testing on windows 8, localhost.


Solution

  • In the latest version of Node, this memory should be deallocated at some point by V8 and this might be done incrementally.

    In previous versions of Node/V8 deallocation was more aggressive and was not done incrementally. The latter wasn't so good for performance.

    Have a listen to this http://nodeup.com/fortyfive

    You can check the version of V8 node is using like this:

    node -e "console.log(process.versions.v8)"
    

    This post will give you plenty of pointers to check for memory leaks in Node.js https://hacks.mozilla.org/2012/11/tracking-down-memory-leaks-in-node-js-a-node-js-holiday-season/

    You can also force GC as detailed here: http://simonmcmanus.wordpress.com/2013/01/03/forcing-garbage-collection-with-node-js-and-v8/