Fixing a hole where the rain gets in …
IE is notorious for leaking memory when using lots of AJAX and DHTML. IE typically leaks memory when you have a script object that forms a circular reference with a DOM element. The garbage collector can not handle this case because there are two different garbage collectors at work.
I spent some of tonight fixing memory leaks in my cube dimension selector control (basically a fancy tree control). I was surprised how straightforward the whole process was. It wouldn’t have been so easy if it weren’t for DRIP, a nice simple tool that detects leftover references to DOM elements when the page unloads.
1. Nested functions always create a closure => refrence to the containing scope. This is the case even if the function is an empty one. I was surprised at this because I thought closures only contained references to variables that were actually used in the function. I’m guessing the closure for an empty function has a pointer to the “this” object.
Solution: Don’t use nested functions. Use the classic event handler registration method. There are some limitations, such as not being able to pass any parameters but it will not likely leak.
elem.onclick = eventHandler;
2. It is very easy to form circular references between script and DOM. Suppose you have a script object that has a reference to a DOM element such as a DIV. If you call appendChild on the DIV your script object will have a reference to the attached element. Now, if on the attached element you use an expando property that references the script object in anyway, you have a cycle!