In jQuery, which is faster, does the selector or equivalent function or depend on it?

I often wondered about using selectors versus equivalent functions in jQuery. By this I mean statements that contain the same components that return identical result sets, but are constructed in different ways.

Take the following example:

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

(Note: the intention is two equivalent queries. If this is not always the same thing, I would appreciate it if you indicated this)

So, given the example above, is there any real difference in speed / performance? Obviously the first one is shorter, so this will reduce the number of bytes loaded / loaded, but Im really not interested in this at the moment.

+4
source share
1 answer

I would say that the first one is faster because it parses only one CSS selector and searches only for children, where the second should parse two, plus it should search for all descendants.

But I wouldnโ€™t worry about something so small. Because JavaScript is very fast in WebKit and Gecko, and still relatively fast in IE, no one will notice the difference.


From what I see when looking at the jQuery / Sizzle source, both parts of the code do the same inside.

The first document.getElementById('FundManager1') ( Sizzle is smart enough to know what #FundManager1 means), and then the search for option is done using this context. The only difference between the two parts of the code is the use of the > selector, causing Sizzle to find only the direct children context, and not all descendants. I guess this is faster since you need to learn only one level of the DOM hierarchy.


Other editing:

The text above applies only to browsers that do not support the document.querySelectorAll(css_selector) method! In browsers that do (WebKit and Gecko, perhaps Opera?), This method is used instead of Sizzle , so the entire CSS syntax selector is made by the browser itself, instead of the jQuery framework, which I'm sure is much faster.

+5
source

All Articles