Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you know what may cause memory leaks in JavaScript?

Tags:

Do you know what may cause memory leaks in JavaScript? I am interested in browsers: IE 7, FireFox 3, Safari 3

like image 904
Michael Dubakov Avatar asked Oct 04 '08 14:10

Michael Dubakov


People also ask

What can cause memory leak in JavaScript?

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.

What is the main cause of memory leaks?

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.


2 Answers

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.

  • JavaScript and memory leaks
  • Introducing the closure
  • More leakage patterns
  • Conclusion

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.

like image 71
jk. Avatar answered Sep 19 '22 18:09

jk.


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; 
like image 41
AnthonyWJones Avatar answered Sep 21 '22 18:09

AnthonyWJones