innerHTML vs replaceHtml vs $.html

JavaScript performance comparison

Test case created by DouglasDuteil and last updated

Info

See http://stevenlevithan.com/demo/replaceHtml.html

Preparation code

<script src="//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

  

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
.innerHTML
ele.innerHTML = testStr
pending…
replaceHtml
ele = replaceHtml(ele, testStr);
pending…
$.html
$ele.html(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. Here’s a list of current revisions for this page:

0 comments

Add a comment