Ben Aston
Ben Aston

Reputation: 55769

Why does this JavaScript cause a memory leak?

The following code is regarded as causing a memory leak because element maintains a reference to function bar and bar maintains a reference to element via closure (if I understand correctly).

Why does this cause a memory leak? Does it only cause a leak when element is a DOM node?

function foo(element, a, b) {
  element.onclick = function bar() { /* uses a and b */ };
}

Upvotes: 0

Views: 96

Answers (2)

jfriend00
jfriend00

Reputation: 707996

This is called a Javascript closure and is an expected feature of Javascript. This is not a memory leak in any modern browser.

If the DOM element represented by element is removed from the DOM, then the onclick handler will be garbage collected and then the closure itself will be garbage collected.

During the lifetime of element, the variables a and b will be part of the closure. This is an expected language feature as they are part of the closure that this code creates. When and if, element is deleted from the DOM and it is garbage collected, the closure and its references a and b will be eligible for garbage collection too.

There are some old browsers that did not always handle this properly, but that is generally not considered a design consideration any more for modern browsers. Further, it only caused an issue of consequence if you ran code like this over and over (removing DOM elements each time too) such that a large enough amount of memory was consumed by things that weren't being garbage collected when they should have been. This typically only happened in long running single page applications that had a lot of dynamic DOM stuff going on. But, as I said with modern browsers, this is no longer an issue as the browser's garbage collector handles this situation now.

Upvotes: 4

user149341
user149341

Reputation:

This code only caused a memory leak in certain old versions of Internet Explorer. Internet Explorer 8 made some changes to memory management which mitigated the problem:

https://msdn.microsoft.com/en-us/library/dd361842(v=vs.85).aspx

As all of the affected versions of Internet Explorer are now thoroughly obsolete, this is no longer an issue you need to be concerned with.

Upvotes: 1

Related Questions