4

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!

Joo Park
  • 3,115
  • 4
  • 27
  • 31

2 Answers2

2

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
  • 12,555
  • 7
  • 49
  • 66
0

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
  • 35,755
  • 9
  • 58
  • 55
  • Was this bug fixed in later / more recent versions of IE? – Julien Chastang Jun 05 '09 at 05:47
  • Seems like they took car of it in IE8: http://msdn.microsoft.com/en-us/library/dd361842(VS.85).aspx Now, all we have to do is wait a decade for people to stop using the old, leaky IE versions :) – gustafc Jun 05 '09 at 10:55
  • 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 Jun 05 '09 at 14:12