Anyone have more insight into the statement "Avoid closures"? Or rather, an alternative to having private functions?
function() {
function() {
function() {
function() {
}
}
}
} var theThing = null;
function replaceThing(){
var oldThing = theThing;
function unused(){ return oldThing }
theThing = {
longStr: new Array(1000000).join('*'),
someMethod: function(){ }
};
}
setInterval(replaceThing, 1000);
V8 (and all other engines I tested) will save the oldThing variable in someMethod's lexical environment record, causing each Thing to keep a reference to the previous Thing, preventing it from being garbage collected. This is despite the fact that the old thing is actually unreachable - someMethod never uses the oldThing variable.For a more detailed explanation, check out the post that I lifted this example from: http://point.davidglasser.net/2013/06/27/surprising-javascri...
var theThing = null;
function replaceThing() {
theThing = {
longStr: Array(1E6).join("*"),
someMethod: function() { }
};
}
setInterval(replaceThing, 1E3);
http://closure-compiler.appspot.com/homeExcessive closures can lead to memory leaks. Anonymous closures are a PITA when debugging.