Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 980
Vivian River Avatar asked Jan 19 '12 16:01

Vivian River


2 Answers

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.

like image 53
user1106925 Avatar answered Sep 18 '22 00:09

user1106925


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.

like image 25
s4y Avatar answered Sep 18 '22 00:09

s4y