Its browser is specific because jQuery uses querySelectorAll when it is available. When I tested in WebKit, it was really faster. As it turned out, querySelectorAll optimized for this case.
Inside WebKit, if the entire selector is #<id> , and the document has only one element with this identifier, it is optimized for getElementById . But if the selector is something else, querySelectorAll moves the document looking for elements that match.
Yes, it should be possible to optimize this case so that they do the same - but right now no one has. You can find it here in the WebKit source, SelectorDataList::execute uses SelectorDataList::canUseIdLookup to decide whether to use getElementById . It looks like this:
if (m_selectors.size() != 1) return false; if (m_selectors[0].selector->m_match != CSSSelector::Id) return false; if (!rootNode->inDocument()) return false; if (rootNode->document()->inQuirksMode()) return false; if (rootNode->document()->containsMultipleElementsWithId(m_selectors[0].selector->value())) return false; return true;
If you tested in a browser other than WebKit, it is possible that it does not have similar optimizations.
s4y
source share