javascript closures: how they start leaking memory
many programmers believe javascript closures starts leaking memory.
I want to see some examples where this happens.
I dont want to see closure being added 开发者_如何学JAVAas events to dom elements and removing dom elements in IE. As in link below
function foo(value) {
var bar = document.getElementById("selector");
bar.attachEvent("onclick",
// closure
function() {
alert(value);
}
);
}
i want to see some other cases where closures may start to leak.
To sum up on jAndy's link (for the full picture still follow the link).
Closures them selfs are not a big problem, the problems comes when you don't understand that the everything in the inherited scopes continues to live on as long as the closure exists.
Example
function doAmazingGrace() {
// gigantic list of stuff!
var list = [...];
var result = magicComputationOnTheList();
// readOnlyResults for whatever reason....
return {
get: function() {
return result;
}
}
}
result
itself is not a problem since it has to live on in order for the closure to work, but list
will be "leaked", unless you loose the reference to the closure it will go away so it's not technically a leak.
But as long as the closure lives on, you keep a reference to list
in there, which isn't needed.
So in order to fix it, it would be wise to use delete list
or list = null
before returning the object, so that the Array can be garbage collected.
The second issue are circular references, but that's not a closure issue, you can always introduce circular references and whether and how long they leak is also dependent on the garbage collectors ability to get rid of them. V8 does a good job at that, old IE versions had extreme problems with it though.
精彩评论