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?
2 Answers
Reset to default 6Because $('#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.
版权声明:本文标题:javascript - jQuery selector: Why is $("#id").find("p") faster than $("#id p&qu 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742364364a2460986.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论