JavaScript memory management pitfalls? JavaScript memory management pitfalls? javascript javascript

JavaScript memory management pitfalls?


From my experience, Garbage Collectors are well/poorly implemented depending on the browser. Applying good Object Oriented programming practices is a good start.

My only advice: do not create memory leaks by connecting DOM & javascript objects (circular references that won't be cleared by DOM and JS GCs). These mistakes will eat far more memory than any object you will instantiate within your application.

More details on DOM/JS memory leaks.http://msdn.microsoft.com/en-us/library/bb250448%28VS.85%29.aspx


  • In IE, at least in older versions, a DOM element was kept in memory after you removed it using removeChild if it had an event listener attached. The only way to remove it from memory was to detach the event before removing it from the DOM.
  • As long as you don't create and remove elements often, you don't really have to worry about this. If you create lots of elements when the application starts, but don't create new objects after that, then don't worry too much about memory leaks.


I think by storing data on DOM nodes you can easily create circular references which not all browsers can deal with. For example:

this.element = document.getElementById('something');this.element.attachedObject = this;