className VS classList Showdown (v23)

Revision 23 of this benchmark created on


Description

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

Preparation HTML

<style type="text/css">
  .blah{color: black;}
  .bleh{font-size: 300px}
  .foo{color:#F00;height:50px;opacity:0.3;} 
  .bar{color:#0F0;height:70px;opacity:0.5;font-size: 900px} 
  .baz{color:#00F;height:90px;opacity:0.7;font-weight: bold}
</style>
<div id="base" class="">
    test 1
</div>

Setup

var node = document.getElementById('base');
    node.className = 'blah bleh';
    var classList = node.classList;
    var i=0;

Test runner

Ready to run.

Testing in
TestOps/sec
classList (naive)
if (i++ % 2 === 0) {
  classList.add('foo');
  classList.add('bar');
  classList.add('baz');
}

else {
  classList.remove('foo');
  classList.remove('bar');
  classList.remove('baz');

}
ready
className (optimized)
if (i++ % 2 === 0) {
  node.className = 'blah bleh foo bar baz';
}

else {
  node.className = 'blah bleh';
}
ready
className + classList (hybrid)
var classes = node.className.split(' ');
var obj = {};
for (var i=0; i < classes.length; i++) {
  obj[classes[i]] = true;
}

if (i++ % 2 === 0) {
  obj['foo'] = true;
  obj['bar'] = true;
  obj['baz'] = true;
  node.className = Object.keys(obj).join(' ');
}

else {
  delete obj['foo'];
  delete obj['bar'];
  delete obj['baz'];
  node.className = Object.keys(obj).join(' ');
}
ready

Revisions

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