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="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>

Preparation code output

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

Test runner

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

Java applet disabled.

Testing in unknown unknown
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. Here’s a list of current revisions for this page:

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.

Konrad Dzwinel commented :

I've reported poor Chrome performance in var a = document.querySelectorAll('.alpha'); as a bug here: https://code.google.com/p/chromium/issues/detail?id=253425

Add a comment