Attribute versus class querying

JavaScript performance comparison

Test case created by Craig Patik

Preparation code

<div>
  <div class="alpha">
    .alpha
  </div>
  <div class="alpha" data-bravo>
    .alpha[bravo]
  </div>
  <div class="alpha" data-bravo="charlie">
    .alpha[bravo="charlie"]
    <div class="alpha">
      .alpha
    </div>
    <div data-bravo>
      [bravo]
    </div>
    <div data-bravo="charlie">
      [bravo="charlie"]
    </div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
    

Preparation code output

<div> <div class="alpha"> .alpha </div> <div class="alpha" data-bravo> .alpha[bravo] </div> <div class="alpha" data-bravo="charlie"> .alpha[bravo="charlie"] <div class="alpha"> .alpha </div> <div data-bravo> [bravo] </div> <div data-bravo="charlie"> [bravo="charlie"] </div> </div> </div>

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
qsa class
var a = document.querySelectorAll('.alpha');
pending…
jQuery class
var b = $('.alpha');
pending…
qsa attr
var c = document.querySelectorAll('[data-bravo]');
pending…
jQuery attr
var d = $('[data-bravo]');
pending…
qsa attr=value
var e = document.querySelectorAll('[data-bravo="charlie"]');
pending…
jQuery attr=value
var f = $('[data-bravo="charlie"]');
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.

3 Comments

Craig Patik (revision owner) commented :

Note that I had to leave out a test for document.getElementsByClassName() because it was a couple orders of magnitude faster so the graph wouldn't show the difference between class and attribute querying.

Konrad Dzwinel commented :

@Craig Patrik - oh, so that's why $('.bla') won over document.querySelectorAll('.bla'). jQuery is probably using document.getElementsByClassName() behind the scenes. I wonder why document.querySelectorAll() doesn't do the same thing.

.alpha
.alpha[bravo]
.alpha[bravo="charlie"]
.alpha
[bravo]
[bravo="charlie"]