A while ago, I was curious how the speed of document.getElementById
compared to document.querySelector
in Javascript for selecting a single element by ID. querySelector
has to do a lot more work, so one would expect that it would be slower, but I didn't know if the difference was enough to care about.
I wrote a little benchmark to test this. You can run it by clicking . This creates 100,000 elements, and then selects them all in a loop. It does this 105 times, and ignores the first 5 results (to avoid caching effects). It then plots a historgram of the average time per function call (in milliseconds) for each run. There is a template string used in the loop that I'm testing, so the exact numbers are slightly inflated, but in a way that is consistent across both functions.
On Firefox 92 on my Linux machine, getElementById
gets a average of 7ms, while querySelector
gets 62ms. Chromium 93 on the same machine does significantly worse, getting around 44ms and 206ms respectively. querySelector
has significantly more variance in both cases, although it's worse in Chromium than it is in Firefox.
Apologies for the janky histograms — the reason I didn't publish this months ago is that Plotly's histograms are essentially completely broken, so I just went and wrote my own thing.
document.getElementById