admin管理员组

文章数量:1334158

The author of this page: 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?

The author of this page: http://24ways/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?

Share Improve this question edited Jul 15, 2013 at 15:49 holographic-principle 19.7k10 gold badges48 silver badges62 bronze badges asked Jan 19, 2012 at 16:50 Vivian RiverVivian River 32.4k64 gold badges210 silver badges323 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

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 e up with different optimizations.

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

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.

本文标签: javascriptjQuery selector Why is (quotidquot)find(quotpquot) faster than (quotid pquot)Stack Overflow