The Browser That Ate My Memory

Have you noticed occasions when your browser suddenly starts eating memory? Even the latest versions of Firefox, Opera or Internet Explorer can cause a PC to grind to a halt by grabbing all available memory. Browsers are greedy by their nature. They grab memory for such things as the Back-Forward cache in order to speed performance. However, they also suffer from JavaScript programming errors that prevent JavaScript and DOM objects from being recycled once they have fallen out of use. This is most likely to happen if you have created reference loops via closures that involve both DOM and JavaScript objects. This normally involves event handlers, but can happen in a variety of circumstances.

JavaScript has its own built-in mark and sweep garbage collection that works pretty well. The programmer does not normally have to explicitly signal that an object needs to be recycled: it is done automatically once all objects that reference the object go out of scope and its resources are released.

The problems happen because most browsers have separate systems for recycling resources in the DOM and JavaScript. The recycling of DOM objects is usually done via a reference-counting system. This system returns the memory to the heap once the reference count falls to zero. If a circular reference is detected within either recycling system, then all is well and the circularity is detected and managed, but if it involves both JavaScript and the DOM, as when a DOM object has a reference back to a closure, such as an event handler, then the objects can’t be released even after the browser has navigated away from the page that caused the problem.

The seasoned JavaScript programmer will break circular references by assigning a null to the reference to the object once the object is no longer required. However, the best solution for the JavaScript programmer is probably to use a framework such as jQuery which manually releases event handlers that are assigned via the framework. This is little consolation to the user who needs to access many sites, few of which have taken any steps to ensure that their JavaScript avoids memory leaks.

Browsers have become so central to the work we do on PCs that we have become increasingly tolerant of the demands that these applications make on PC memory. However, it seems absurd that one should need to keep closing and re-starting the browser just to prevent the memory-drain from throttling the PC. It is particularly galling when the cause is programming error.

Do you have any ideas on how the browsers excessive appetite for memory can be suppressed? It would be great to hear what you think.