Hacker News new | ask | show | jobs
by greggman3 1665 days ago
I'm getting getElementById is 2x to 4x faster than querySelector depending on the browser

https://jsbenchit.org/?src=25e097f939f76b559b2515430fb5e459

I'm a little surprised. Sure i'd expected getElementById to be faster but honestly I'd have expected browser implementation of querySelector to do a relatively trivial up front check, is the selector a simple id, if so, call getElementById. I suppose that adds overheads to all queries, but that's true of many types of "best case" optimizations. (in the best case it's faster but adds some overhead for any non-best case)

Still, I don't care about this level of optimization. I'll just contuinue to use querySelector everywhere because it's more flexable. No code I've ever written looks up so many elements in a single interaction that this micro optimization would ever matter to me.

3 comments

Browsers do exactly the optimization you're describing: https://source.chromium.org/chromium/chromium/src/+/main:thi...

Both getElementById and querySelector are quite fast, down to the level of measuring individual branches in a micro benchmark. querySelector does have to do a bit more work to lookup the cached query and a handful of extra branches over getElementById, it's not scanning the document for an ID query unless you're in quirks mode though.

Flexible is a double-edged sword. `querySelector` is bringing in the added complexity of selector syntax, which is more stuff to think about that isn't relevant to what you're trying to do.

For example now you have to worry about whether there are any characters in the ID that need escaping in a selector (eg `.`), something that may not be easy to verify when formatting an ID out of variables.

So I'd suggest preferring getElementById for its directness, rather than for micro-optimisation reasons.

(In principle the same should be true for getElementsByClassName, but the live NodeLists returned by that method are a trap for the unwary, so neither option is ideal.)

> No code I've ever written looks up so many elements in a single interaction that this micro optimization would ever matter to me.

Exactly. This is the type of nano-optimization that is pretty common to see in e.g. SO answers. Sure, selecting _a hundred thousand_ items in a loop might be some milliseconds faster, but so what? How often are you selecting more than a few at most?