innerHTML vs replaceHtml vs $.html

Benchmark created by DouglasDuteil on


Description

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

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<pre id="text" style="height : 200px;">
  
</pre>

Setup

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);

Test runner

Ready to run.

Testing in
TestOps/sec
.innerHTML
ele.innerHTML = testStr
ready
replaceHtml
ele = replaceHtml(ele, testStr);
ready
$.html
$ele.html(testStr)
ready

Revisions

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

  • Revision 1: published by DouglasDuteil on
  • Revision 3: published by witcher42 on
  • Revision 4: published by AjiTae on