Categories
closures javascript memory-leaks node.js

Closure and callback memory leak in javascript

function(foo, cb) {
var bigObject = new BigObject();
doFoo(foo, function(e) {
if (e.type === bigObject.type) {
cb();
// bigObject = null;
}
});
}

The above example shows a classic, accidental (or maybe not) memory-leaking closure. The V8 garbage collector can’t determine if it’s safe to remove the bigObject because it’s being used in the callback function which can be called several times.

One solution is to set bigObject to null when the job in the callback function is over. But if you are using many variables (imagine there is n variables like bigObject, and they are all used in callback) then cleaning this becomes an ugly problem.

My question is this: is there any other way to clean those used variables?

EDIT Here’s another (real world) example: So I get application from mongodb and compare it to some other application. Callback from mongodb uses variable application that is defined out of that callback. After I get result from mongodb I return it also as a callback (because it is all async and I cant just write return ). So actually it can happen that i propagate callback all the way to the source…

function compareApplications(application, condition, callback) {
var model = database.getModel('Application');
model.find(condition, function (err, applicationFromMongo) {
var result = (applicationFromMongo.applicationID == application.applicationID)
callback(result)
}
}