Why is 1 faster than 2?
$('#p1').find('span');
$('#p1 span');
Why is 1 faster than 2?
$('#p1').find('span');
$('#p1 span');
The best way is to test!
From this simple test:
<p id="p1"><span>Test</span></p>
Version: jQuery 1.4.2
$('#p1').find('span');
: 2601ms
$('#p1 span');
: 1998msIt appears that the single selector is faster in this case, since you're not making as many calls through jQuery this makes sense.
Give it a try here, look at your console.
In cae you're on jQuery 1.3.2 here's those results:
$('#p1').find('span');
: 3225ms$('#p1 span');
: 2082msIn your case, perhaps #1 is faster than #2, but depending on how many iterations and how many elements to search, #2 could very well be faster than #1 in other scenarios.
E.g.: I would guess if you had 3 span
elements and no other elements in #p1
, then #1 would be faster than #2, since find isn't trying to do as much CSS matching. But, if you had 1000 span
elements, along with 2000 other elements in #p1
, I'll bet #2 would be faster, since it doesn't have to iterate over every element twice.
In jQuery 1.4 the selector is checked if it is an id
selector (like your #p1
).
document.getElementId(...)
is called and result is wrapped in jQuery utility object and returned.