innerHTML vs replaceHtml vs $.html vs $.text

JavaScript performance comparison

Revision 3 of this test case created by witcher42

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<pre id="text" style="height : 200px;">
  
</pre>
      
<script>
Benchmark.prototype.setup = function() {
  var ele = document.getElementById("text");
  
  var tenElsStr = "<b>1</b><i>2</i><b>3</b><i>4</i><b>5</b><i>6</i><b>7</b><i>8</i><b>9</b><i> </i>";
  
  
  function multiply (str, num) {
  	return Array(num + 1).join(str);
  }
  
  
  // This is much faster than simple use of innerHTML in some browsers
  // See <http://blog.stevenlevithan.com/archives/faster-than-innerhtml>
  
  
  function replaceHtml(el, html) {
    var oldEl = el;
  /*@cc_on // Pure innerHTML is slightly faster in IE
  		oldEl.innerHTML = html;
  		return oldEl;
  	@*/
    var newEl = oldEl.cloneNode(false);
    newEl.innerHTML = html;
    oldEl.parentNode.replaceChild(newEl, oldEl);
  /* Since we just removed the old element from the DOM, return a reference
  	to the new element, which can be used to restore variable references. */
    return newEl;
  }
  
  
  var testStr = multiply(tenElsStr, 1000);
  var $ele = $(ele);
  

};
</script>

Preparation code output

<pre id="text" style="height : 200px;"> </pre>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
.innerHTML
ele.innerHTML = testStr
pending…
replaceHtml
ele = replaceHtml(ele, testStr);
pending…
$.html
$ele.html(testStr)
pending…
$.text
$ele.text(testStr)
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments