hasClass vs is so

JavaScript performance comparison

Revision 7 of this test case created

Info

To confirm a question asked here:

http://stackoverflow.com/questions/4901553/jquery-hasclass-vs-is

I believe hasClass should be faster.

But using element.className is much faster still

Preparation code

<div id="foo">
  I am a DIV
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var a = $('#foo'),
        b = a.get(0);
   
};
</script>

Preparation code output

I am a DIV

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
a.hasClass('bar');
pending…
is
a.is('.bar');
pending…
className (regex)
/(^|\W)bar(\W|$)/ig.test(b.className);
pending…
className (string)
(' ' + b.className + ' ').indexOf(' bar ') !== -1
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