className VS classList Showdown

JavaScript performance comparison

Revision 3 of this test case created by Jason Miller

Info

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

Preparation code

<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>
<script>
Benchmark.prototype.setup = function() {
    var node = document.getElementById('base'),
        className = 'baz';
   
    function addClass_className(el, className) {
        var cn = el.className || '',
            c = ' '+cn+' ',
            p = ' '+className+' ';
        if (c.indexOf(p)===-1) {
            el.className = cn + (cn ? ' ' : '') + className;
        }
    }
   
   
    function removeClass_className(el, className) {
        var cn = el.className || '',
            c = ' '+cn+' ',
            p = ' '+className+' ';
        if (c.indexOf(p)!==-1) {
            c = c.replace(p,' ');
            el.className = c.substring(1, c.length-2);
        }
    }
   
    function addClass_classList(el, className) {
        el.classList.add(className);
    }
   
    function removeClass_classList(el, className) {
        el.classList.remove(className);
    }
};
</script>

Preparation code output

test 1
test 2 test 3

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
classList
addClass_classList(node, 'foo');
addClass_classList(node, 'foo');
addClass_classList(node, 'foo');
addClass_classList(node, 'bar');
addClass_classList(node, 'baz');
removeClass_classList(node, 'foo');
removeClass_classList(node, 'foo');
removeClass_classList(node, 'foo');
removeClass_classList(node, 'bar');
removeClass_classList(node, 'baz');
 
pending…
className RegExp


addClass_className(node, 'foo');
addClass_className(node, 'foo');
addClass_className(node, 'foo');
addClass_className(node, 'bar');
addClass_className(node, 'baz');
removeClass_className(node, 'foo');
removeClass_className(node, 'foo');
removeClass_className(node, 'foo');
removeClass_className(node, 'bar');
removeClass_className(node, 'baz');
 
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment