JQuery selector: Why $ ("# id"). find ("p") is faster than $ ("# id p").

The author of this page: http://24ways.org/2011/your-jquery-now-with-less-suck claims that the jQuery selector $('#id').find('p') faster than $('#id p') , although they seem to give the same results, if I understand correctly. What is the reason for this difference?

+7
source share
2 answers

Because $('#id').find('p') optimized to execute ...

 document.getElementById('id').getElementsByTagName('p'); 

... whereas I assume that $('#id p') will use querySelectorAll if it is available, or a JavaScript-based selection mechanism if not.


It should be noted that performance always has differences between browsers. Opera is known to have a very fast querySelectorAll .

In addition, different versions of jQuery may have different optimizations.

It is possible that $('#id p') will be (or currently) with the same optimization as the first version.

+6
source

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.

+2
source

All Articles