jquery is vs hasclass vs pure

JavaScript performance comparison

Revision 9 of this test case created

Info

Added TestCase6, to also test pureJS in a "class not existent matter". Added variable "target" to ensure, the get()/getElementById process doesn't count towards the tests Added pureJS indexOf instead of regex.

Preparation code

<a class="someClass" id="someElement" href="#">link</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  var $t = $("#someElement");
  var target = $t.get(0);
 
  function hasClass(el, selector) {
   var className = " " + selector + " ";
 
   if ((" " + el.className + " ").replace(/[\n\t]/g, " ").indexOf(className) > -1) {
    return true;
   }
 
   return false;
  }

function hasClass2(element, className) {
    return (' ' + element.className +  ' ').indexOf(' ' + className + ' ') > -1;
}
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
is
$t.is(".someClass");
pending…
hasClass
$t.hasClass("someClass");
pending…
pureJs
hasClass(target, 'someClass');
pending…
is non existing
$t.is(".otherClass");
pending…
hasClass non existing
$t.hasClass("otherClass");
pending…
pureJs non existing
hasClass(target, 'otherClass');
pending…
pureJs hasClass2
hasClass2(target, 'someClass')
pending…
pureJs hasClass2 non-existing
hasClass2(target, 'otherClass')
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