views:

716

answers:

3

I have been reading up to try to make sense of memory leaks in browsers, esp. IE. I understand that the leaks are caused by a mismatch in garbage collection algorithms between the Javascript engine and the DOM object tree, and will persist past. What I don't understand is why (according to some statements in the articles I'm reading) the memory is not reclaimed after the page is unloaded by the browser. Navigating away from a webpage should put all the DOM and javascript objects out of scope at that point, shouldn't it?

+2  A: 

The best thing I ever read about Javascript memory leaks was written by Doulgas Crockford.

To answer your question, yes, the browser absolutely should unload all the objects (and most importantly, event handlers) at the appropriate time. If it did, it wouldnt have leaks :)

Josh Stodola
+1  A: 

You don't have to make sense of them -- they are bugs in broswers and being fixed from versions to versions.

J-16 SDiZ
+3  A: 

Here's the problem. IE has a separate garbage collector for the DOM and for javascript. They can't detect circular references between the two.

What we used to was to clean up all event handlers from all nodes at page unload. This could, however, halt the browser while unloading. This only addressed the case where the circular reference was caused by event handlers. It could also be caused by adding direct references from DOM nodes to js objects which had a reference to the DOM node itself.

Another good thing to remember is that if you are deleting nodes, it's a good idea to remove the handlers yourself first. Ext-js has a Ext.destroy method that does just that (if you've set the handlers using ext).

Example

// Leaky code to wrap HTML elements that allows you to find the custom js object by adding 
//a reference as an "expando" property
function El(node) {
  this.dom = node;
  node.el = this;
}

Then Microsoft hacked IE so it removed all event handlers and expando properties when unloading internally, therefore it's much faster than doing it with js. This fix seemed to fix our memory problems, but not all problems as there are people still having the problem.

MS's description of the problem

MS releases patch that "fixes" memory leaks:

Blog about fixed memory leaks

IE still has some problems

At our company, we use ext-js. By always setting event handlers using ext-js, which has a an internal clean up routine, we have not experienced memory leaks. In reality, memory usage grows but stops at about 250Mb for a machine with 4Gb of RAM. We don't think that's too bad since we load about 2Mb(uncompressed) of js files and all the elements on the page are dynamic.

There's a lot to be said about this and we've researched this extensively where I work. Feel free to ask a more specific question. I may be able to help you.

Juan Mendes