querySelectorAll class names vs attributes

JavaScript performance comparison

Revision 2 of this test case created by Jim Montgomery

Info

Curious to see if there is any perf diff between querySelectorAll('.cat.bobtail') and querySelectorAll('[data-cat="bobtail"]'), because I would rather use more meaningful data- attribute than some arbitrary class names.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="sektion">
</div>
<script>
var f = document.createDocumentFragment(), div, sektion = document.getElementById('sektion');
for (var i = 0; i < 500; i++) {
  div = document.createElement('div');
  div.className = 'foo bar'+i;
  div.setAttribute('sekt','bar'+i);
  f.appendChild(div);
};
sektion.appendChild(f);
</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
document.querySelectorAll('.foo');
document.querySelectorAll('.foo');
pending…
document.querySelectorAll('[class~="foo"]');
document.querySelectorAll('[class~="foo"]');
pending…
document.querySelectorAll('[class~=bar1],[class~=bar2],[class~=bar3]');
document.querySelectorAll('[class~=bar1],[class~=bar2],[class~=bar3]');
pending…
document.querySelectorAll('.bar1,.bar2,.bar3');
document.querySelectorAll('.bar1,.bar2,.bar3');
pending…
document.querySelectorAll('[sekt^=bar]');
document.querySelectorAll('[sekt^=bar]'); // same as .foo
pending…
jQuery('.bar1,.bar2,.bar3');
jQuery('.bar1,.bar2,.bar3');
pending…
jQuery('[class~=bar1],[class~=bar2],[class~=bar3]');
jQuery('[class~=bar1],[class~=bar2],[class~=bar3]');
pending…
jQuery('[class~=bar1]').add('[class~=bar2]').add('[class~=bar3]');
jQuery('[class~=bar1]').add('[class~=bar2]').add('[class~=bar3]');
pending…
jQuery('[class~=bar1]').add('[class~=bar2],[class~=bar3]');
jQuery('[class~=bar1]').add('[class~=bar2],[class~=bar3]');
pending…
document.querySelectorAll('[sekt=bar1],[sekt=bar2],[sekt=bar3]');
document.querySelectorAll('[sekt=bar1],[sekt=bar2],[sekt=bar3]');
pending…
jQuery('[sekt=bar1],[sekt=bar2],[sekt=bar3]');
jQuery('[sekt=bar1],[sekt=bar2],[sekt=bar3]');
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