classList vs addClass

JavaScript performance comparison

Revision 7 of this test case created by

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/);
   for (var e = 0; e < this.length; e++) {
     this[e].classList.add.apply(this[e].classList, classes);
   }
   return this;
  };
  
  $.fn.hasFromClassList = function(str) {
     for (var e = 0; e < this.length; e++) {
        if (this[e].classList.contains(str)) return true;
     }
     return false;
  };

  $.fn.removeFromClassList = function(str) {
  
   var classes = str.split(/\s/);  
   for (var e = 0; e < this.length; e++) {
     this[e].classList.remove.apply(this[e].classList, classes);
   }
   return this;
  };
</script>
    

Preparation code output

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("kappa");
pending…
jQuery.fn.addClass
$b.addClass(listStr)
pending…
jQuery.fn.removeClass
$b.removeClass("kappa")
pending…
jQuery.fn.hasClass
$b.hasClass("gamma");
pending…
classList hasFromClassList
$a.hasFromClassList("gamma");
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