Recently, I wrote a web 2.0 style mashup.  When I deployed, it worked great, except that some users would see browser crashes after a while.  Looking closer, it looked like there was a memory leak, my web app was using up browser memory and not releasing it.  Now, I'm not a bad coder, and it usually takes a pretty basic flaw to have a memory leak in a garbage-collected language like javascript.  Scanning my code, showed no obvious errors.  All my generated javascript objects were neatly discarded. I wasn't accidentally adding things to the DOM, where they could hang out for ever. I had no ever growing lists or tables that would keep references to objects to they wouldn't be GC'd.

But I did have a problem:  A circular reference.   IE has a very basic flaw in its garbage collector. It uses reference counting, and if there's a circular reference, the collector can't collect the objects.  If object A points to object B and B (directly or indirectly) points to A, A and B can never be GC'd. 

One of the Javascript idioms is to use function closures as callbacks. The closures give the callback access to the locally scoped variables where the function closure was declared.  However, this closure forms a circular reference, and without special care, will cause a memory leak on IE.  Every time a callback is added to an object (an image.onload for example), a circular reference is created.  If the object involved happens to be something large like an image (as it was in my case), the leak can become pretty obvious pretty quickly.  It is easy to break the circular reference (by removing the callback from the object when the callback is invoked), but of course, if you don't know about this problem, there's no reason to do it.

The Javascript closure idiom is pervasive in the web 2.0 world.  I wonder how many web apps out there have memory leaks when running on IE due to IEs flaw in its garbage collector.  There's a more detailed description of this problem on Jiberings page on Javascript closures.  (or you can look at the other million or so pages on this topic: google javascript ie memory leak closure.)


Comments:

Post a Comment:
Comments are closed for this entry.

This blog copyright 2010 by plamere