removeClass methods

JavaScript performance comparison

Test case created by Tom

Preparation code

<div id="test1" class="a b c">Test 1</div>
<div id="test2" class="a b c">Test 2</div>
<div id="test3" class="a b c">Test 3</div>
      
<script>
Benchmark.prototype.setup = function() {
  var el1 = document.getElementById('test1'),
    el2 = document.getElementById('test2'),
    el3 = document.getElementById('test3');
  
  HTMLElement.prototype.removeClass1 = function(sClassToRemove) {
    var sClassName = '',
      aClasses = this.className.split(' ');
    for (var i=0, imax=aClasses.length; i<imax; ++i) {
      if (!aClasses[i]) continue;  // Account for class="a  b"
      if (aClasses[i]!==sClassToRemove) sClassName += aClasses[i] + ' ';
    }
    this.className = sClassName.trim();
  };
  
  HTMLElement.prototype.removeClass2 = function(sClassToRemove) {
    var aNewClasses = [],
      aOldClasses = this.className.split(' ');
    for (var i=0, imax=aOldClasses.length; i<imax; ++i) {
      if (!aOldClasses[i]) continue;  // Account for class="a  b"
      if (aOldClasses[i]!==sClassToRemove) aNewClasses.push(aOldClasses[i]);
    }
    this.className = aNewClasses.join(' ');
  };
  
  HTMLElement.prototype.removeClass3 = function(sClassToRemove) {
    var re = new RegExp(sClassToRemove + '\\s*', 'gi');
    this.className = this.className.replace(re, '').trim();
  };

};

Benchmark.prototype.teardown = function() {
  el1.className = 'a b c';
  el2.className = 'a b c';
  el3.className = 'a b c';

};
</script>

Preparation code output

<div id="test1" class="a b c">Test 1</div> <div id="test2" class="a b c">Test 2</div> <div id="test3" class="a b c">Test 3</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
String
el1.removeClass1('b');
pending…
Array
el2.removeClass2('b');
pending…
RegExp
el3.removeClass3('b');
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

Test 1
Test 2
Test 3