Question

I'm into selectors performance lately, and it's bugging me that the browsers which currently implements the Selectors API don't use document.getElementById when a simple #id is being passed.

The performance penalty is huge, so library authors continue to implement their own way around that.

Any ideas?

Was it helpful?

Solution

After making my comment above, I decided to follow through:

From Node.cpp in the Chromium source

if (strictParsing && inDocument() && querySelectorList.hasOneSelector() && querySelectorList.first()->m_match == CSSSelector::Id) {
    Element* element = document()->getElementById(querySelectorList.first()->m_value);
    if (element && (isDocumentNode() || element->isDescendantOf(this)) && selectorChecker.checkSelector(querySelectorList.first(), element))
        return element;
    return 0;
}

So it does map on getElementById, it is just that parsing the string looking for selectors is an expensive operation.

OTHER TIPS

Tbh. the performance penalty is insignificant... I really doubt you're going to do 100.000 id lookups per second, if you do, then QSA performance is actually the last thing you should look at.

As to why, adding an extra if/else might make id lookups more performant, but then other css selectors will be a fraction (still insignificant) slower. Why optimize QSA to deal with id lookups when there's a specialist method to do exactly that a lot faster anyways.

In any case, browsers are aiming for speed and leaving out stuff like this makes the overall performance charts look a lot better. In this benchmark race it's REALLY about every single millisecond, but for the developers... please be realistic, other benchmarks are more important, QSA performance shouldn't really be a factor anymore.

As for developer convenience, it works, it's still so fast you won't notice it in actual applications (I challenge you to show me where it's IS VISUALLY noticable whilst still being a sane program ;o).

Maybe because if they did that, they would have to add a check to see if its a simple id query (no modifiers) which would slow down every other query? It might not be a huge performance hit to do the test, but its difficult to speak for other developers.

I think if you are worried about it you can add a func like getObByID that checks for document,getElementById, uses it if it exists, else uses the selector. Maybe the developers don't feel the need to add this type of abstraction when you can easily do it yourself, and it would be up to developers to remember to use it, and increase learning curve.

I was comparing getElementById() and querySelector() and found that someone has already done performance comparisons and calculations.

It certainly looks as though querySelector() wins every time... and by a considerable amount.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top