If I do something like
// global scope
function stuff() {
// local scope
var a = new SomeHugeMemoryHog();
}
// a doesn't exist down here, but what happened to the memory from the "stuff" scope?
Will I create a memory leak if I don’t set a = null at the end of the stuff scope? Or should I not worry about it? I’m asking this question with emphasis on creating DOM objects (such as a canvas) inside the scope of functions (which I don’t use later at any time). I’m only using the canvas to grab vector dimensions.
As others have pointed out that since there is no reference to
aoutside the function the garbage collector will collect it, most likely on the next collection.Some things you need to watch out for, however, is indirect capture. A common place this happens is in event handlers through closure capture. For example,
Even if the nested function doesn’t use
a.amight be kept alive because the activation record ofstuffis still alive. Also, DOM objects might be collected differently than normal JavaScript objects which might cause them to be susceptible circular referneces causing collection problems. This most problematic in older browsers and since you reference using a canvas browsers that support canvas tend to be more modern and correctly handle circular references as well as allowing local variables not captured by a closure to collect.