views:

80

answers:

1

I've often wondered about the use of selectors versus equivalent functions in jQuery. By this I mean statements that comprise the same components that return identical result sets, but are constructed differently.

Take the following example:

alert($("#FundManager1>option").length);
alert($("#FundManager1").find("option").length);

(Note: the intention is for two equivalent queries - If these are not always the same, I would be grateful if you could point this out)

So, given the example above, is there any real difference in speed/performance? Obviously, the former is shorter, so will result in fewer uploaded/downloaded bytes, but I’m not really interested in that at the moment.

+5  A: 

I would say the first is faster, as it parses only one CSS selector and only looks for children, where the second one has to parse two, plus has to look for all descendants.

But I wouldn't bother for something so small. As JavaScript is really fast in WebKit and Gecko, and still relatively fast in IE, no-one will ever notice the difference.


From what I can see by looking at the jQuery/Sizzle source, both pieces of code do the same internally.

First document.getElementById('FundManager1') is executed (Sizzle is smart enough to know that's what #FundManager1 means), and then the search for option is done using that as context. The only difference between the two pieces of code is the use of the > selector, causing Sizzle to search for just the context's direct children, and not all descendants. I assume this faster, as only one level of DOM hierarchy has to be explored.


Another edit:

The text above only applies to browsers that don't support the document.querySelectorAll(css_selector) method! In browsers that do (WebKit and Gecko, maybe Opera?) this method is used instead of Sizzle, so that all CSS selector parsing is done by the browser itself, instead of the jQuery framework, which I'm sure is a lot faster.

Douwe Maan
Nice answer. (filler goes here)
jensgram
Diving into / Analyzing other people's code is always fun ;-) Especially when it's good code.
Douwe Maan