Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does manual garbage collection of DOM elements in jquery improve browser performance at all?

with scope on performance, does it make any sense to remove elements that are not longer needed? or do browsers perform auto garbage collection on dom elements, that are not further referenced in code?

$('some_element').fadeOut(1000, function(el){
   $(el).remove(); // <-- does this make sense at all?
});
like image 863
maddrag0n Avatar asked Feb 05 '12 22:02

maddrag0n


2 Answers

This code:

$('some_element').remove();

tells the browser that you are done with that element and no longer need it in the DOM. If you don't have any other references in your javascript to that element, the garbage collector will then free the memory that it uses.

If you do not remove it, then the DOM element stays in your web page for as long as that web page is displayed. It will never be garbage collected because the browser has no way of knowing whether you intend for it to stay in the page or not.

It is a good practice to manually remove DOM elements that are no longer needed.

But, in 99% of the cases, it will not matter in any way because the memory used by one DOM element is trivial compared to the overall memory used by a web page. Everything in the web page will be freed when the user goes to another web page anyway.

The main time that it does make a significant difference to free something like this is when you are doing the same operation over and over again (in a big loop, on a timer, etc...). In that case, you do not want objects to pile up and consume increasing amounts of memory as the page is used.

like image 136
jfriend00 Avatar answered Oct 15 '22 22:10

jfriend00


Yes, it makes sense.

GC should only kick in when there are no references to the DOM element. Whilst it is still a part of the DOM (display: none doesn't actually remove it), it will consume memory, from the DOM portion to event handlers, etc.

If your intention is to fade out the element and remove the element (possibly no longer needed or removal of DOM clutter), then use the code in your example.

like image 45
alex Avatar answered Oct 15 '22 20:10

alex