Has anybody bench marked selecting elements with id's and class's from CSS and javascript?
It would make sense that an element with an id is faster to select than if it had a class even if it was the only element with that class.
Do I really need to be concerned?
When searching for an id
, the selector will halt as soon as it's found a match (even if there are many) - I assume there's some sort of key/value lookup table for this purpose, as it's much faster than DOM traversal. Here's why , and here's an excerpt:
It's still much better to select by ID...because jQuery uses the browser's native method (getElementByID) to do this and doesn't have to do any of it's own DOM traversal, which is much faster.
The linked results there show >100x speed improvement with id
vs class
.
When searching for a class
, the entire DOM (or scope) is searched. Here's a benchmark using scope .
You can benchmark selectors in your own browser here .
I don't think you should be really that concerned : selecting by id
and selection by class
just don't have the same meaning :
id
class
.
Still, here's a benchmark that could interest you : Speed/validity selectors test for frameworks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.