user213154
user213154

Reputation:

jQuery selector performance: $('#a p') versus $('p', $context) versus $context.find('p')

If I have already got, in my variable $a_div, a jQuery object for the DIV in the following markup and I want to find the Ps

<div id="a">
    ...
    <p>...</p>
    ...
</div>

Is there a significant performance difference between these ways to select the P elements in the DIV?

$('#a p')
$('p', $a_div)
$a_div.find('p')

And if so, do you know why?

Upvotes: 2

Views: 833

Answers (2)

user113716
user113716

Reputation: 322542

This sort of thing is usually browser dependent, but I'd use the 3rd one.

First one, browsers with querySelectorAll will make use of it, so performance should be good.

In browsers that don't support qsa, I think Sizzle finds all p elements on the page, and traverses their ancestors to see if there's a #a element.

$('#a p')

I wouldn't use the second one at all, because it gets changed to the third one in the background.

$('p', $a_div)   // becomes $a_div.find('p')

Whether via querySelectorAll or getElementsByTagName, you're starting from a known point in the DOM, and only searching within it, so I'd bet that this will generally be fastest.

$a_div.find('p')

Upvotes: 6

Dogbert
Dogbert

Reputation: 222288

You can always test it out - http://jsperf.com/some-jquery-selectors-performance-tests

Second one seems to be about thrice as fast as the first one, and third one slightly more. This would definitely differ depending on the rest of your HTML structure, but I'm pretty sure the first one will always remain the slowest.

Upvotes: 2

Related Questions