className VS classList Showdown (v8)

Revision 8 of this benchmark created on


Description

How much faster is classList.add/remove than className regex manipulation?

Preparation HTML

<style type="text/css">
  .foo { color:#F00; height:100px; opacity:0.3; } .bar { color:#0F0; height:200px;
  opacity:0.5; } .baz { color:#00F; height:300px; opacity:0.7; }
</style>
<div id="base" class="foo bar">
  <div class="foo bar baz">
    test 1
  </div>
  <span class="foo bar">
    test 2
  </span>
  <span class="baz">
    test 3
  </span>
</div>

Setup

var node = document.getElementById('base'),
        className = 'baz';
    
    function addClass_className(el, className) {
      el.className += " " + className;
    }
    
    
    function removeClass_className(ele, cls) {
      var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
      ele.className = ele.className.replace(reg, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''); //last 2 replaces do right trim (see http://blog.stevenlevithan.com/archives/faster-trim-javascript)
    }

Teardown


    node.className = '';
  

Test runner

Ready to run.

Testing in
TestOps/sec
classList (add)
node.className = '';
node.classList.add('foo');
node.classList.add('bar');
node.classList.add('baz');
node.classList.add('kar');
ready
One by one
node.className = '';
node.className += ' foo';
node.className += ' bar';
node.className += ' baz';
node.className += ' kar';
ready
className raw
node.className = '';
node.className = 'foo bar baz kar';
ready

Revisions

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