views:

71

answers:

3

Why is 1 faster than 2?

  1. $('#p1').find('span');
  2. $('#p1 span');
+1  A: 

The best way is to test!

From this simple test:

  • Content - ​<p id="p1"><span>Test</span></p>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
  • Looping 100,000 times
  • Version: jQuery 1.4.2

  • $('#p1').find('span');: 2601ms

  • $('#p1 span');: 1998ms

It 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');: 2082ms

Try it out with 1.3.2 here.

Nick Craver
+1 for jsFiddle
Homer
A: 

In 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.

palswim
A: 

In jQuery 1.4 the selector is checked if it is an id selector (like your #p1).

  • If it indeed is, the document.getElementId(...) is called and result is wrapped in jQuery utility object and returned.
  • If it is anything other than that, jQuery calls Sizzle which then does whatever it does to find the elements. And, judging from the source, this is pretty non-trivial stuff.
Marko Dumic