jQuery selector: Why is $(“#id”).find(“p”) faster

2019-04-26 16:12发布

问题:

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

回答1:

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

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

...whereas I'm guessing $('#id p') will either use querySelectorAll if available, or the JavaScript based selector engine if not.


You should note that performance always has variations between browsers. Opera is known to have an extremely fast querySelectorAll.

Also, different versions of jQuery may come up with different optimizations.

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



回答2:

It’s browser specific since jQuery uses querySelectorAll when it’s available. When I tested in WebKit it was indeed faster. As it turns out querySelectorAll is optimized for this case.

Inside WebKit, if the whole selector is #<id> and there is only one element in the document with that id, it’s optimized to getElementById. But, if the selector is anything else, querySelectorAll traverses the document looking for elements which match.

Yep, it should be possible to optimize this case so that they perform 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 were testing in a non-WebKit browser, it’s possible that it is missing similar optimizations.