ClassList versus ClassName

JavaScript performance comparison

Revision 4 of this test case created by

Preparation code

<div id="foo"></div>
<script>fooEl = document.getElementById('foo');</script>

      
<script>
Benchmark.prototype.setup = function() {
  fooEl.className = ' aaaa bbbb cccc dddd '; 
  //note the leading and trailing spaces

};
</script>

Preparation code output

<div id="foo"></div>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
classList.remove
fooEl.classList.remove('aaaa');
pending…
className.replace
fooEl.className = fooEl.className.replace('aaaa ', ' ');
pending…
classList.add
fooEl.classList.add('zzzz');
pending…
className +=
//apple to apple comparison requires a check for duplicate class... to use speedy indexOf check requires fragile leading and trailing space convention in className strings to ensure you're not matching a piece of the className (this could also be done with regexp word boundaries)...

if( fooEl.className.indexOf(' zzzz ') === -1 ){
    fooEl.className += 'zzzz ';
}
pending…
className.replace (many) + cleanup
fooEl.className = fooEl.className.replace('aaaa ', ' ').replace('bbbb ', ' ').replace('cccc ', ' ').replace('dddd ',' ').replace('  ',' ');

//the final replace is ensure proper clean up of all the extra spaces left behind, keeping one for the leading-trailing space convention mentioned above
pending…
classList.remove (many)
fooEl.classList.remove('aaaa');
fooEl.classList.remove('bbbb');
fooEl.classList.remove('cccc');
fooEl.classList.remove('dddd');
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.

0 Comments