Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you dispose of jQuery objects?

A colleague of mine always sets their jQuery variables to null, to effectively dispose them, once they're finished with, e.g:

var bigThing = $(body);
// ...
// Do some stuff
// ...
bigThing = null;

Is that really necessary?

like image 975
Jay Avatar asked Jan 05 '12 09:01

Jay


2 Answers

If you encapsulate your code into functions thats unnecessary as after the function finishes the local variables will be killed anyway when no reference of them is used elsewhere.

Holding onto a selector/variable (caching) might have some positive effect tho if you need to select the same thing over and over again versus selecting it only once and keeping the variable.

like image 188
bardiir Avatar answered Sep 30 '22 18:09

bardiir


Short answer: no that's hardly ever necessary if you're using jQuery.

It depends on what you did with it. If you didn't attach any event handlers to the DOM Node, the garbage collector will clear it when it's no longer referenced.

But even if you did attach event handlers, jQuery will take care of them in functions like .remove() and .empty() by detaching all event handlers for you. So as long as you use jQuery to interact with the DOM, you're safe.

Without jQuery, if you've attached an event handler to the Node, the GC won't clear it, even after you've removed the Node from the DOM tree and you no longer have any references to it. This is because the DOM Node contains a reference to a JavaScript object (i.e. the event handler) and vice versa. This creates a cyclic reference across two separate systems; something most garbage collectors have trouble with.

For further reading I point you to Douglas Crockford's article on Memory Leaks.

like image 20
Peter-Paul van Gemerden Avatar answered Sep 30 '22 20:09

Peter-Paul van Gemerden