greggreg
greggreg

Reputation: 12085

javascript: make sure objects in closure are garbage collected

I'm trying to make sure some vars wrapped in a closure will be released for garbage collection when I'm done with them. I'm unsure weather setting them to undefined, or deleting them would be sufficient. Any thoughts?

// run once for each photo, could be hundreds
$("img.photo").each( function(){
    // create the vars to put in the callback
    var photo = $(this);
    var tmp = new Image();

    // set the callback, wrapping the vars in its scope
    tmp.onload = (function(p,t){
      return function(){ 
        // do some stuff

        // mark the vars for garbage collection
        t.onload = ?
        t = ?
        p = ?
    })(photo, tmp)

    // set the source, which calls onload when loaded
    tmp.src = photo.attr("src")
})

Upvotes: 4

Views: 4343

Answers (3)

Arvind Singh
Arvind Singh

Reputation: 792

JavaScript takes care of the variables whose scope has left execution for those variable declared with var keyword.

For object declared use delete keyword to release memory.

x = new Object;
alert(x.value);
delete (x);
alert(x); //this wouldn't show

You may also find something at What is JavaScript garbage collection?.

Upvotes: -3

Marshall
Marshall

Reputation: 4766

look at this post for some more details on garbage collection.

Since you are sending an anonymous function to .each the function and all within will be garbage collected. Except for one part:

// set the callback, wrapping the vars in its scope
tmp.onload = (function(p,t){
  return function(){ 
    // do some stuff

    // mark the vars for garbage collection
    t.onload = ?
    t = ?
    p = ?
})(photo, tmp)

The function (function(p,t){ ... })(photo, tmp) will be collected since it is anonymous and no longer referenced. But the function it returns will be added to tmp.onload which will persist.

If you want to make sure things are collected set variables, when you are done with them, to undefined or null. That way the garbage collector will be sure that there is no reference in scope, thus freeing them.

Upvotes: 7

Pointy
Pointy

Reputation: 413826

When your "onload" function exits, nothing will be referencing the closure itself, so the whole thing will be collected.

Upvotes: 2

Related Questions