jQuery .empty() vs .html('') 差別

效能上來說 .empty() 速度會比 .html('') 還要快。

Test

console.time() console.timeEnd() 簡單測試

<div id="test">Hello World!!!</div>
<div id="test2">Hello World!!!</div>

<script type="text/javascript" src="./js/jquery-3.1.1.js"></script>
<script type="text/javascript">

console.time('empty');
$('#test').empty();
console.timeEnd('empty'); // empty: 0.269ms

console.time('html');
$('#test2').html('');
console.timeEnd('html'); // html: 0.675ms

</script>

Diffenence between source code

.empty()

empty: function() {
  var elem,
    i = 0;

  for ( ; ( elem = this[ i ] ) != null; i++ ) {
    if ( elem.nodeType === 1 ) {

      // Prevent memory leaks
      jQuery.cleanData( getAll( elem, false ) );

      // Remove any remaining nodes
      elem.textContent = "";
    }
  }

  return this;
},

.html(“)

html: function( value ) {
  return access( this, function( value ) {
    var elem = this[ 0 ] || {},
      i = 0,
      l = this.length;

    if ( value === undefined && elem.nodeType === 1 ) {
      return elem.innerHTML;
    }

    // See if we can take a shortcut and just use innerHTML
    if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
      !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

      value = jQuery.htmlPrefilter( value );

      try {
        for ( ; i < l; i++ ) {
          elem = this[ i ] || {};

          // Remove element nodes and prevent memory leaks
          if ( elem.nodeType === 1 ) {
            jQuery.cleanData( getAll( elem, false ) );
            elem.innerHTML = value;
          }
        }

        elem = 0;

      // If using innerHTML throws an exception, use the fallback method
      } catch ( e ) {}
    }

    if ( elem ) {
      this.empty().append( value );
    }
  }, null, value, arguments.length );
},