JavaScript – Why Do Browsers Leak Memory?

chromefirefoxinternet explorerjavascript

A colleague and I were speaking about browsers (using a browser control object in a project), and it appears as plain as day that all browsers (Firefox, Chrome, IE, Opera) display the same characteristic or side-effect from their usage and that being 'Leaking Memory'.

Can someone explain why that is the case? Surely as with any form of code, there should be proper garbage collection?

PS. I've read about some defensive patterns on why this can happen from a developer's perspective. I am aware of an article Crockford wrote on IE; but why is the problem symptomatic of every browser?
Thanks

Best Answer

There are 4 places a browser can leak memory:

The web page

In modern browsers this is fully up to the web developer. Garbage-collected environments don't collect memory that is still being referenced to, and there are a lot of ways to keep referencing memory without meaning to (e.g. create a closure to attach as an event handler and accidentally include a bunch of variables in that closure's scope). A web developer can solve these leaks completely by properly handling variable references in their code. A page reload typically frees up the memory.

Add-ons

If add-ons are also written in a garbage-collected language (like javascript), then they suffer from the same issue. However a page reload will typically not free up this memory, so it appears as if the browser is leaking memory whereas it's actually the add-on developer's fault. To my knowledge this is the biggest cause of browser leaks (which is why the default recommendation is to test whether the leak occurs without add-ons).

Browser engine

All modern browser engines are written in C++. C++ is not garbage-collected, but uses explicit memory allocation instead. If developers allocate memory and then forget to deallocate it, the engine leaks memory. To my knowledge all the browser makers do a lot of testing and code review to find and solve these kinds of leaks. It's not 100% fixed, and never will be, but it's not a huge problem anymore.

Non-leaks

Finally there are a range of caching features that mean the browser's process will grow in scope while using it. These aren't leaks, they're intended to optimally make use of available RAM. Typically the memory footprint grows to a maximum and then hovers there.

Related Topic