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!

- 11,165
- 9
- 62
- 113
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)
-
1Both cases suck btw, you're registering an event on every element when event bubbling could be used. – Florian Margaine Apr 25 '12 at 14:57