When we started testing our NodeJS project we noticed huge memory consuption. It is caused by memory leaks all over our project. So we started looking for all the causes that can produce memory leaks. There are some answers to that question on stackoverflow, but there isn't any straitforward document on what is and what isn't a memory leak.
My questions :
Does the V8 GC collect variables that aren't used but there is a function closure below them? Example:
var serviceChannel = require('./channel');
var dataRegistration = require('../data/registration');
function registerOnChannel(userID, channelID, callsuccess, callerror) {
serviceChannel.findChannel(channelID, function (channel) {
if (!channel) {
callerror("Channel doesn' exists");
return;
}
dataRegistration.registerOnChannel(userID, channelID, function (registration) {
if (!registration) {
callerror("Registration doesn' exists");
return;
}
callsuccess("Registration successful");
}, function (error) {
callerror("Error on registration");
})
}, function (error) {
callerror("Error on finding channel");
})
}
So, serviceChannel and dataRegistration will be kept in memory as long as registerOnChanel is live. But will the variable channel be deleted by the GC (it isn't used by any function)?
First I'd say you should move your API to use the built in EventEmitter (http://nodejs.org/api/events.html).
Does the V8 GC collect variables that aren't used but there is a function closure below them?
If you use a variable from a previous function scope then the variable will have to stick around until the containing function scope, and all callbacks containing that variable, have gone out of scope.
But will the variable channel be deleted by the GC (it isn't used by any function)?
Based on the code example you've posted, yes it will be collected by GC. But it's very possible to have leaked a reference or two without noticing.