Hacker News new | ask | show | jobs
by libria 1670 days ago
In the worst case

> around 44ms and 206ms

so around 162ms difference per 100,000 elements. This doesn't concern most of us for anything less than 1,000 elements (1.62ms).

I use querySelector more often simply for aesthetics (consistent with other calls and qsAll).

1 comments

I would prefer getElementById regardless of its performance because you may need escaping for CSS selectors, for example `getElementById('comment:1234')` vs. `querySelector('#comment\\:1234')`.
You could avoid that quite easily by using IDs that don't need escaping though.

That said, the fact escaping is necessary could point to part of the reason why querySelector is slower. There's obviously some additional parsing necessary just to work out what the developer is requesting. If you don't need to spend that CPU time then it's certainly better not to.

This is my subjective opinion, but I think getElementById makes the code easier to understand when you scan the code. Even if the query selector is simple, it still requires you to read the query to understand it's just a simple lookup by id