23

Do you know what may cause memory leaks in JavaScript? I am interested in browsers: IE 7, FireFox 3, Safari 3

Michael Dubakov
  • 1,560
  • 3
  • 16
  • 25

5 Answers5

35

There is a nice article about JavaScript and memory leaks. It does not specific about on browser, it rather describes the whole problematic of memory leaks and JavaScript.

I think it is a better approach to be as browser unspecific as possible insted of optimizing for a few browsers, when developing a website for the public.

jk.
  • 6,388
  • 2
  • 26
  • 21
  • Excellent article on the subject. +1 – AnthonyWJones Oct 04 '08 at 14:56
  • And for whoever might be interested in IE8, it might be worth to know that most of the example explained in the article are not leaking memory in IE8 anymore. Should read this: http://stackoverflow.com/questions/1999840/javascript-circular-references-and-memory-leaks/2000467#2000467 – Marco Demaio Sep 08 '10 at 12:45
22

Here is a classic memory leak in IE:-

function body_onload()
{
    var elem = document.getElementById('someElementId');
    // do stuff with elem
    elem.onclick = function() {
        //Some code that doesn't need the elem variable
    }
 }

After this code has run there is circular reference because an element has a function assigned its onclick event which references a scope object which in turn holds a reference to element.

someElement->onclick->function-scope->elem->someElement

In IE DOM elements are COM based reference counting objects that the Javascript GC can't cleanup.

The addition of a final line in the above code would clean it up:-

var elem = null;
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
3

In general; circular references are the cause of many problems. I remember IE 6 (not sure if it applies to 7) leaking quite badly with XMLHTTP... setting onreadystatechange = null once it was finished with fixed it.

Greg
  • 316,276
  • 54
  • 369
  • 333
  • Yes the problem applies to 7. And you can't assign null since its not a function you need a void function function() {} that has been created in the global scope and/or assign null to variable holding a reference to the xmlhttp object. – AnthonyWJones Oct 04 '08 at 14:58
2

You're dealing with 2 kinds of objects (and 2 garbage collectors), javascript and DOM objects, which can reference each other (the circular reference), and then neither GC can take care of all its objects even when the page unloads. Here's a good description:

http://getben.com/archive/2006/05/30/Resolving-JavaScript-Memory-Leaks.aspx

http://www.josh-davis.org/2007/04/11/javascript-built-in-listeners-and-memory-leaks/

Gene T
  • 5,156
  • 1
  • 24
  • 24
1

You can check this MSDN article for Internet Explorer memory leak patterns. Also there are some tools for detecting memory leaks:

Atanas Korchev
  • 30,562
  • 8
  • 59
  • 93