Do you know what may cause memory leaks in JavaScript? I am interested in browsers: IE 7, FireFox 3, Safari 3
The main cause of memory leaks in an application is due to unwanted references. The garbage collector finds the memory that is no longer in use by the program and releases it back to the operating system for further allocation.
A memory leak starts when a program requests a chunk of memory from the operating system for itself and its data. As a program operates, it sometimes needs more memory and makes an additional request.
There is a nice article about JavaScript and memory leaks. It does not specific about on browser, it rather describes the whole problematic of memory leaks and JavaScript.
I think it is a better approach to be as browser unspecific as possible insted of optimizing for a few browsers, when developing a website for the public.
Here is a classic memory leak in IE:-
function body_onload() { var elem = document.getElementById('someElementId'); // do stuff with elem elem.onclick = function() { //Some code that doesn't need the elem variable } }
After this code has run there is circular reference because an element has a function assigned its onclick event which references a scope object which in turn holds a reference to element.
someElement->onclick->function-scope->elem->someElement
In IE DOM elements are COM based reference counting objects that the Javascript GC can't cleanup.
The addition of a final line in the above code would clean it up:-
var elem = null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With