querySelectorAll vs getElementById

JavaScript performance comparison

Revision 8 of this test case created by Thomas Fuchs

Preparation code

<p id="foo">bar</p>
<script>
  var IDENTIFIER = /^#[a-zA-Z-_]+$/;
</script>

Preparation code output

bar

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
querySelectorAll
var result = document.querySelectorAll('#foo');
pending…
getElementById
var result = document.getElementById('foo');
pending…
on demand
var id = '#foo',
    result = IDENTIFIER.test(id) ? [document.getElementById(id.substr(1))] : document.querySelectorAll(id);
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:

2 comments

Thomas Fuchs (revision owner) commented :

Note it's not really exactly the same, especially when there's nothing found.

But it seems by special-casing (which could be further optimized!) it's easy to have at least a 2x performance improvement.

sean commented :

How come chrome 18 is faster than chrome 20?

Add a comment