Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some common ways to cause memory leaks using JQuery/JavaScript?

My question assumes you are creating a web page that will be displayed for a "long time." I'm curious as to what are some of the common gotchas that will cause memory leaks when using JQuery/JavaScript in such a scenario? For instance what happens in terms of memory when you call $.remove() on a collection of elements? Thanks!

like image 725
Achilles Avatar asked Apr 25 '12 14:04

Achilles


People also ask

What causes 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 are the causes of memory leaks?

A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code (i.e. unreachable memory). A memory leak has symptoms similar to a number of other problems and generally can only be diagnosed by a programmer with access to the program's source code.

Can you leak memory using JavaScript?

Memory leaks can and do happen in garbage collected languages such as JavaScript. These can go unnoticed for some time, and eventually they will wreak havoc. For this reason, memory profiling tools are essential for finding memory leaks.


1 Answers

JavaScript uses garbage collection to reclaim the memory occupied by strings, objects, arrays, and functions that are no longer in use. This frees you, the programmer, from having to explicitly deallocate memory yourself and is an important part of what makes JavaScript programming easier than, say, C programming.

References : Check this for more and an answer on SO.

Memory issues in event registering mechanism MDN

var i;  
var els = document.getElementsByTagName('*');  

// Case 1  
for(i=0 ; i<els.length ; i++){  
    els[i].addEventListener("click", function(e){/*do something*/}, false});  
}  

// Case 2  
function processEvent(e){  
    /*do something*/  
}  

for(i=0 ; i<els.length ; i++){  
  els[i].addEventListener("click", processEvent, false});  
}  

In the first case, a new (anonymous) function is created at each loop turn. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, since no reference to the anonymous functions is kept, it is not possible to call element.removeEventListener because we do not have a reference to the handler, while in the second case, it's possible to do

myElement.removeEventListener("click", processEvent, false)
like image 121
The Alpha Avatar answered Oct 07 '22 03:10

The Alpha