getElementById vs. querySelector

JavaScript performance comparison

Test case created by Ara Pehlivanian

Info

Compare the speed of getElementById to querySelector

Preparation code

<p id="foo">Foo</p>
<p id="bar">Bar</p>
<p id="baz">Baz</p>

Preparation code output

Foo

Bar

Baz

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
getElementById
var bar = document.getElementById("bar");
pending…
querySelector
var bar = document.querySelector("#bar");
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:

5 comments

Spamme commented :

Interesting, I was actually looking for something else, a benchmark between the document methods querySelector and evaluate. It would be interesting if you add to your test also the xpath search technique, not every browser is implementing it but if I'm not wrong firefox, opera, safari and chrome have implemented it, as usual ie doesn't follow the standards but who care?

Xpath to get an element by id: //*[@id='bar'] JavaScript code: document.evaluate("//*[@id='bar']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

Krishnan commented :

You saved me from using querySelctor. I am new to web development. How do you arrive at the speed calculation? I could understood one thing that querySelector is way behind getElementById. But how do you arrive at this conclusion. Just typically running a timer to test that?

wes commented :

Interesting, I was under the impression IE9 does not support querySelector(), which is the search that led me to this page. Do you have some other Javascript library installed for this support in IE9???

Eric commented :

What I wonder is what is faster in this situation:

#id1
-#id2
 -<tag>
  -#id3
  -#id4
  -#id5



var id3 = document.getElementById( "id3" );
var id4 = document.getElementById( "id3" );
var id5 = document.getElementById( "id3" );

OR

var id2 = document.getElementById( "id2" );
var id3 = id2.querySelector( "#id3" );
var id4 = id2.querySelector( "#id4" );
var id5 = id2.querySelector( "#id5" );

Add a comment