className VS classList Showdown (v18)

Revision 18 of this benchmark created by Andrey Sklyarevskiy 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 = node.className;
    
    function addClass_className(el, className) {
      if (el.className.indexOf(className) == -1) {
         el.className += " " + className;
      }
    }
    
    function addClass_className2(el, className) {
      el.className = [el.className, className].join(' ');
    }
    
    
    function removeClass_className(ele, cls) {
      var reg = new RegExp('\\b' + cls + '\\b');
      ele.className = ele.className.replace(reg, '')
    }

Test runner

Ready to run.

Testing in
TestOps/sec
classList (add)
var classList = node.classList;
classList.add('foo');
classList.add('bar');
classList.add('baz');
node.className=className;
ready
className (add) walkontable 0.2.0
addClass_className(node, 'foo');
addClass_className(node, 'bar');
addClass_className(node, 'baz');
node.className=className;
ready
className2 (add)
addClass_className2(node, 'foo');
addClass_className2(node, 'bar');
addClass_className2(node, 'baz');
node.className=className;
ready

Revisions

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