1

为什么1比2快?

  1. $('#p1').find('span');
  2. $('#p1 span');
4

3 回答 3

1
于 2010-08-18T18:55:25.740 回答
1

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.
于 2010-08-18T19:18:42.693 回答
0

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.

于 2010-08-18T19:01:48.517 回答