Skip to content

Instantly share code, notes, and snippets.

@Filirom1
Forked from vvo/gist:2488897
Created May 3, 2012 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Filirom1/2584366 to your computer and use it in GitHub Desktop.
Save Filirom1/2584366 to your computer and use it in GitHub Desktop.
mem leak ? on('error', function(){

http.get + req.on('error', function(){}) seems to provoke a memory leak:

node --expose-gc leak.js
We should do 5 requests
2MB used
Done: 0/5, not yet GC: 0
26MB used
Done: 5/5, not yet GC: 5
all requests done, memory should be collected by now ?
26MB used
Done: 5/5, not yet GC: 5
all requests done, memory should be collected by now ?

With the fix

node --expose-gc leak.js
We should do 5 requests
2MB used
Done: 0/5, not yet GC: 0
26MB used
Done: 5/5, not yet GC: 0
all requests done, memory should be collected by now ?
var http = require('http'),
weak = require('weak'),
done = 0,
count = 0,
countGC = 0,
todo = 5;
console.log('We should do '+ todo +' requests');
// show memused and progress while running
setInterval(status, 5000);status();
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000, '127.0.0.1', getall);
function getall() {
for(var i = 0; i < todo; i++) {
(function(){
// creates a big buffer
var megabig = new Big();
weak(megabig, afterGC);
// this should not trigger a memory leak but it does when using http.get
function cb() {
done+=1;
return megabig;
}
http.get({
hostname: 'localhost',
pathname: '/index.html?' + Math.random(),
port: 3000,
protocol: 'http:'
}, cb).on('error', function(e) {
cb(e);
});
})()
}
}
function Big() {
count ++;
this.yo = (new Buffer(1 * 1024 * 1024 * 3)).toString();
}
function afterGC(){
countGC ++
}
function status() {
gc()
console.log((process.memoryUsage().heapUsed/1024/1024).toFixed() + 'MB used');
console.log('Done: '+ done +'/'+ todo + ', not yet GC: ' + (count - countGC));
if (done === todo) {
console.log('all requests done, memory should be collected by now ?')
}
}
setTimeout(function(){}, 1000000000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment