ClassList versus ClassName

JavaScript performance comparison

Revision 6 of this test case created by

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var fooEl = document.createElement("div");
  fooEl.className = ' aaaa bbbb cccc dddd ';
  // with the leading and trailing spaces
  
  var nowhitespaceEl = document.createElement("div");
  nowhitespaceEl.className = 'aaaa bbbb cccc dddd';
  // without the leading and trailing spaces
  
  var rtrim = /^\s+|\s+$/g;

};

Benchmark.prototype.teardown = function() {
  fooEl = null;

};
</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
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…
className.replace with trim
nowhitespaceEl.className = (' ' + nowhitespaceEl.className + ' ').replace(' ' + 'aaaa' + ' ', ' ').replace(rtrim, '');
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