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")
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With