classList vs addClass

JavaScript performance comparison

Test case created by Rick Waldron

Preparation code

<script src="https://code.jquery.com/jquery-git.js"></script>
 

<script>
  var listStr = "alpha beta delta gamma epsilon zeta eta theta iota kappa",
      thismany = 500,
      $a = $(false),
      $b = $(false);
  
  while (thismany--) {
   $a.push($('<div/>').appendTo('body')[0]);
   $b.push($('<div/>').appendTo('body')[0]);
  }
  
  
  //  Create functions to wrap up the behaviour that 
  //  native classList would need to enforce to be
  //  equally tested against jQuery.
  //  jQuery allows for multiple classes
  //  to be passed as a string
  $.fn.addToClassList = function(str) {
  
   var classes = str.split(/\s/),
       classLen = classes.length;
  
  
   for (var e = 0; e < this.length; e++) {
    for (var i = 0; i < classLen; i++) {
     this[e].classList.add(classes[i]);
    }
   }
   return this;
  };
  
  $.fn.removeFromClassList = function(str) {
  
   var classes = str.split(/\s/),
       classLen = classes.length;
  
   for (var e = 0; e < this.length; e++) {
    for (var i = 0; i < classLen; i++) {
     this[e].classList.remove(classes[i]);
    }
   }
   return this;
  };
</script>
    

Preparation code output

<script> var listStr = "alpha beta delta gamma epsilon zeta eta theta iota kappa", thismany = 500, $a = $(false), $b = $(false); while (thismany--) { $a.push($('<div/>').appendTo('body')[0]); $b.push($('<div/>').appendTo('body')[0]); } // Create functions to wrap up the behaviour that // native classList would need to enforce to be // equally tested against jQuery. // jQuery allows for multiple classes // to be passed as a string $.fn.addToClassList = function(str) { var classes = str.split(/\s/), classLen = classes.length; for (var e = 0; e < this.length; e++) { for (var i = 0; i < classLen; i++) { this[e].classList.add(classes[i]); } } return this; }; $.fn.removeFromClassList = function(str) { var classes = str.split(/\s/), classLen = classes.length; for (var e = 0; e < this.length; e++) { for (var i = 0; i < classLen; i++) { this[e].classList.remove(classes[i]); } } return this; }; </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 addClassToList
$a.addToClassList(listStr);
pending…
classList removeClassFromList
$a.removeFromClassList("beta gamma zeta theta kappa");
pending…
jQuery.fn.addClass
$b.addClass(listStr)
pending…
jQuery.fn.removeClass
$b.removeClass("beta gamma zeta theta kappa")
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