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 classic, accidental (or maybe not) memory-leaking closure. v8 garbage collector can't determine if it's safe remove bigobject because it's being used in callback function can called several times.

one solution set bigobject null when job in callback function over. if using many variables (imagine there n variables bigobject, , used in callback) cleaning becomes ugly problem.

my question this: there other way clean used variables?

edit here's (real world) example: application mongodb , compare other application. callback mongodb uses variable application defined out of callback. after result mongodb return callback (because async , cant write return ). can happen propagate callback way 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)             } } 

if callback function supposed called once, should unsubscribe after called. release callback + closure gc. closure released, bigobject free collected gc.

that's best solution - noted, gc doesn't magically know callback called once.


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -