Skip to content

Fixing a hole where the rain gets in …

February 19, 2007

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.

During my work I found out some new things (new to me) about JavaScript that I wasn’t aware of.

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!


IE: where’s my memory?
JavaScript closures for dummies
Understanding and solving Internet Explorer leak patterns

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: