Set Node Text

Benchmark created by Jason Miller on


Description

Finding the fastest way to update the textual (non-HTML) contents of an HTML element.

Setup

var el = document.createElement('span');
    document.body.appendChild(el);
    
    var strings = [
        "Test string 1.",
        "Test string 2.",
        "Third string test",
        "A fourth for <em>testing</em>",
        "Maybe one with a <div>div</div>",
        "Just good 'ol plaintext here, folks.",
        "And one with a line break.",
        "Some more text"
      ],
      str,
      len = strings.length,
      c = -1,
      n;

Teardown


    el.parentNode.removeChild(el);
  

Test runner

Ready to run.

Testing in
TestOps/sec
Basic textContent
// Accounts for previous innerHTML use
str = strings[c=(c+1)%len];
el.textContent = str;
ready
TextNode
// Does not account for previous innerHTML use
str = strings[c=(c+1)%len];
n = el.firstChild;
if (n) {
  el.removeChild(n);
}
el.appendChild(document.createTextNode(str));
 
ready
TextNode textContent
// Does not account for previous innerHTML use
str = strings[c=(c+1)%len];
n = el.firstChild;
if (n) {
  n.textContent = str;
}
else {
  el.appendChild(document.createTextNode(str));
}
ready
TextNode textContent +unHTML Support
// A nice compromise: blows out any existing HTML but is 
// as fast as the previous test when no HTML has been used.
str = strings[c=(c+1)%len];
if (el.childNodes.length===1) {
  el.firstChild.textContent = str;
}
else {
  el.textContent = str;
}
ready

Revisions

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

  • Revision 1: published by Jason Miller on