Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance: jQuery remove() vs JavaScript removeChild()

I have a table which contains about 1,500 rows.

I'm removing the table from the DOM with the following jQuery code:

$('#myTable').remove();

which takes about 300ms, creating a quite noticeable lag.

Doing the same thing with removeChild():

var myTable = $('#myTable')[0] ;
myTable.parentNode.removeChild(myTable);

takes about 30ms.

I can easy use the removeChild() version, but I was puzzled why jQuery's remove() would take so much longer? Is the removeChild() version not clearing something that jQuery is?

Demo: jspref

like image 581
Kong Avatar asked Feb 17 '23 19:02

Kong


1 Answers

From the documentation :

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

This means :

  • that this function does some extra work (mainly calling cleanData for itself and the childs)
  • that you should generally use it to avoid memory leaks

This appears clearly in the source code :

remove: function( selector, keepData ) {
    var elem,
        i = 0;

    for ( ; (elem = this[i]) != null; i++ ) {
        if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) {
            if ( !keepData && elem.nodeType === 1 ) {
                jQuery.cleanData( getAll( elem ) );
            }

            if ( elem.parentNode ) {
                if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
                    setGlobalEval( getAll( elem, "script" ) );
                }
                elem.parentNode.removeChild( elem );
            }
        }
    }

    return this;
}
like image 113
Denys Séguret Avatar answered Feb 19 '23 10:02

Denys Séguret