ClassList versus ClassName

JavaScript performance comparison

Test case created by Steve King

Preparation code

<div id="foo"
></div>
<script>
 fooEl = document.getElementById('foo');
</script><script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  fooEl.className = 'aaaa bbbb cccc dddd';
  jFooEl = jQuery(fooEl);

};
</script>

Preparation code output

<div id="foo" ></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

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
Class List
var x = false;
fooEl.classList.add('bbbb');    // duplicate
fooEl.classList.remove('eeee'); // not found
fooEl.classList.add('ffff');    // actually adds
if(fooEl.classList.contains('cccc')) {
  x = true;
}
pending…
jQuery Class Name
var x = false;
jFooEl.addClass('bbbb');    // duplicate
jFooEl.removeClass('eeee'); // not found
jFooEl.addClass('ffff');    // actually adds
if(jFooEl.hasClass('cccc')) {
  x = true;
}
pending…
Raw Class Name
var indexOf;

if((' ' + fooEl.className + ' ').indexOf(' bbbb ') < 0)
 fooEl.className += ' bbbb';

var classArray = fooEl.className.split(/\s+/),
    indexOf = classArray.indexOf('eeee');

if(indexOf >= 0) {
 classArray.splice(indexOf,1);
 fooEl.className = classArray.join(' ');
}

if((' ' + fooEl.className + ' ').indexOf(' ffff ') < 0)
 fooEl.className += ' ffff';

if((' ' + fooEl.className + ' ').indexOf(' cccc ') >= 0) {
  x = true;
}
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