Javascript Memory Leaks
A while ago we were implementing a large, web based, data gathering application for a government department. The application required quite complicated cross field validation and very specific visual feedback mechanisms which had to be live on the page whenever possible. We had already been developing a tag library to extend the bind tags provided out of the box in Spring MVC so we decided to bite the bullet and integrate validation into these tags (I will write more on this project in other entries).
We made extensive use of the Prototype and Behaviour Javascript libraries to assist in cross browser compatibility and to try and keep as much Javascript event code off the page as possible. We soon began to see performance problems in IE. For quite a wile we couldn’t pin down what was making this problem occur as it seemed quite intermittent, but eventually we pinned it down to browsers which had been open on our application for extended lengths of time without being closed and re-opened.
Checking the memory footprint of IE we quickly noted that it’s size was growing at the rate of almost .5 mb per page load. After a fair bit of analysis we discovered a tool called Drip which we found invaluable in tracking down and plugging the leaks.
Two main issues are at the core of memory leaks in IE and the drip link above provides links to sites which discuss both of them.
1. Closures: Briefly closures occur when functions reference variables scoped at higher levels.
2.Event listeners with references to the DOM: Briefly this causes self referencing islands which IE is unable to garbage collect.
Issue number 2 is fixed relatively easy by the event cache javascript a link to which can be found on the drip page I have already linked. The problem of closures is far less difficult to fix but can easily be detected using the drip tool.
There are two possible remedies once you find closures which are leaking memory. The first is to alter your code to remove them altogether. Unfortunately this is not always easy to do or can involve extremely verbose workarounds. In instances where you are attaching an anonymous function to an element (something that we often do when using Behaviour) you will almost invariably create a closure which will leak in IE. We found this closure script to work extremely efficiently in removing these leaks in IE.