views:

485

answers:

3

I read in Jquery in Action that memory leaks can result from javascript closures.

"Unintended closures can have unintended consequences. For example, circular references can lead to memory leaks. A classic example of this is the creation of DOM elements that refer back to closure variables, preventing those variables from being reclaimed."

could somebody give an example of this?

thank you!

+2  A: 

I'd recommend this lecture which provides as well a clever workaround.

http://laurens.vd.oever.nl/weblog/items2005/closures/

SleepyCod
+1 also see http://www.ibm.com/developerworks/web/library/wa-memleak/ for more explanations if needed
Dror
+1  A: 

Here, onClick has a closure which keeps reference to element. By assigning onClick to element.click the circle is created: element -> onClick -> element -> onClick...

function addClickHandler(element) {
    element.click = function onClick(e) {
        alert("Clicked the " + element.nodeName)
    }
}

In some (most? certainly not all) javascript engines the garbage collector will not collect an object that has even a single reference to it. Even if element is removed from the DOM, the circular self-reference above would prevent element and onClick from being collected, thus the memory leak.

Chadwick
A: 

The specific issue is event handlers in IE. Basically if you make an event handler than captures the node it is attached to inside its scope chain then IE will never collect either of them. This is a bug in IE due to its use of refcounting rather than pure GC for liveness.

olliej
Was this bug fixed in later / more recent versions of IE?
Julien Chastang
Seems like they took car of it in IE8: http://msdn.microsoft.com/en-us/library/dd361842(VS.85).aspxNow, all we have to do is wait a decade for people to stop using the old, leaky IE versions :)
gustafc
The worst is the first release of IE6. And what's scary is that some people never applied the patch that improved things somewhat.
Nosredna