getElementById vs. querySelector
JavaScript performance comparison
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.
| Test | Ops/sec | |
|---|---|---|
getElementById |
|
pending… |
querySelector |
|
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:
- Revision 1: published by Ara Pehlivanian
- Revision 3: published
- Revision 4: published
- Revision 5: published
- Revision 6: published
- Revision 7: published
- Revision 8: published by vamp
- Revision 9: published
- Revision 10: published
- Revision 11: published
- Revision 12: published
- Revision 14: published
- Revision 15: published by Name64
- Revision 16: published
- Revision 17: published
- Revision 18: published
- Revision 19: published
- Revision 20: published
- Revision 21: published
- Revision 22: published
- Revision 23: published
- Revision 24: published
- Revision 25: published
- Revision 26: published
- Revision 27: published
- Revision 28: published by dc
- Revision 30: published
- Revision 31: published
- Revision 32: published
- Revision 33: published by AjiTae
- Revision 34: published by AjiTae
5 comments
Interesting, I was actually looking for something else, a benchmark between the
documentmethodsquerySelectorandevaluate. 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);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 thatquerySelectoris way behindgetElementById. But how do you arrive at this conclusion. Just typically running a timer to test that?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???
IE8 and up support the Selectors API (implementation bugs aside). See http://caniuse.com/queryselector for more details.
What I wonder is what is faster in this situation:
OR