hasClass-vs-is

JavaScript performance comparison

Revision 2 of this test case created by Dzylon

Preparation code

<span class="class1 class2">
  Element
</span>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var element = $('span');
};
</script>

Preparation code output

Element

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
hasClass (2 classes)
if (element.hasClass('class1') || element.hasClass('class2')) {
  console.log("hasClass");
}
pending…
is (2 classes)
if (element.is('.class1, .class2')) {
  console.log("is");
}
pending…
hasClass (5 classes)
if (element.hasClass('class1') || element.hasClass('class2') || element.hasClass('class3') || element.hasClass('class4') || element.hasClass('class5')) {
  console.log("hasClass");
}
pending…
is (5 classes)
if (element.is('.class1, .class2, .class3, .class4, .class5')) {
  console.log("is");
}
pending…
hasClass (20 classes)
if (element.hasClass('class1') || element.hasClass('class2') || element.hasClass('class3') || element.hasClass('class4') || element.hasClass('class5') || element.hasClass('class6') || element.hasClass('class7') || element.hasClass('class8') || element.hasClass('class9') || element.hasClass('class10') || element.hasClass('class11') || element.hasClass('class12') || element.hasClass('class13') || element.hasClass('class14') || element.hasClass('class15') || element.hasClass('class16') || element.hasClass('class17') || element.hasClass('class18') || element.hasClass('class19') || element.hasClass('class20')) {
  console.log("hasClass");
}
pending…
is (20 classes)
if (element.is('.class1, .class2, .class3, .class4, .class5, .class6, .class7, .class8, .class9, .class10, .class11, .class12, .class13, .class14, .class15, .class16, .class17, .class18, .class19, .class20')) {
  console.log("is");
}
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. Here’s a list of current revisions for this page:

0 comments

Add a comment