JavaScript JavaScript and the DOM Getting a Handle on the DOM Using CSS Queries to Select Page Elements

Performance?

Does querySelector use up more resources or take longer than using the other selectors getElementById, or getElementsByClassName?

I think they are more or less equally performant if you compare the right things. When you use querySelector and you do a query on a class than you should compare with getElementByClassName, if you do a query on an id, you should compare with getElementById.

1 Answer

Ivan Chwalik
Ivan Chwalik
92 Points

An excellent question. Getting really technical, you'll have to read the specifications on both these functions since it's dependent on the JavaScript engine in use. StackOverflow on the getElementById methodology JavaScript Engines Long story short, querySelector no doubt requires more processing. This makes sense because of it's ability to process all kinds of selector strings which means a more complex function. The getElementById function is much simpler since it's more direct when searching; getElementById is only looking through IDs.

You can absolutely perform the test to determine the answer in your own case too. It would be interesting to run this test on different JavaScript engines (like testing on Chrome/Edge which uses V8 and Firefox which uses SpiderMonkey). You can use console.time('Label') and console.timeEnd('Label') to measure the speed of these functions.

console.time("QuerySelector");
document.querySelector('#firstDiv');
console.timeEnd("QuerySelector");
console.time("GetByID");
document.getElementById('firstDiv');
console.timeEnd("GetByID");

Checking the console in Microsoft Edge DevTools reveals the result: QuerySelector: 0.067138671875 ms GetByID: 0.01708984375 ms

Note that these speeds can change depending on many, many other factors. You'll never get the same result, but you will notice that getElementById is faster.