Reputation: 1068
In terms of browser performance, should I chain selector calls? Does jQuery do a full document search regardless?
For example the difference between $('.my_thing') and $('#outer_div .my_thing')
Upvotes: 0
Views: 202
Reputation: 7434
Another one:
'#id' selector is the fastest and find is the browser native method
$('#outer_div').find('.my_thing');
// or shorthand
$('.my_thing', '#outer_div');
Upvotes: 0
Reputation: 18273
I suggest you to read this article on 24ways: Your jQuery: Now With 67% Less Suck. especially the Selector optimization part.
As you will see in modern browsers the class selectors are really fast, but not in < IE8.
I recommend not to use $('#outer_div .my_thing')
, much better $('#outer_div').find('.my_thing')
.
Upvotes: 1
Reputation: 38173
Common sense says the first example, because the second example requires the extra step of finding the first element and then traversing its DOM branch until it finds the second element.
Imagine you are searching the DOM for the first element, you could actually pass the second element (that you are looking for) because the loop's terminal condition is finding the first element.
As with most performance tweaks, the improvements will be browser-dependent.
Related:
Fastest selector method in jquery and CSS - ID or not?
Upvotes: 0
Reputation: 26921
Here's some useful articles on the topic:
http://blog.bigbinary.com/2010/02/15/how-jquery-selects-elements-using-sizzle.html http://dumitruglavan.com/jquery-performance-tips-cheat-sheet/ http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-think-right-to-left-with-jquery/
To sum up, with introduction of Sizzle, the mentioned queries should give roughly the same performance numbers. If you use older versions, first approach should be faster.
Upvotes: 0
Reputation: 382102
It entirely depends on the selector.
In your case, assuming you don't have .my_thing
elements outside of #outer_div
, both selectors will be very fast as they'll use the underlying getElementsByTagName
.
You're comparing two very fast selectors here, so the difference doesn't really matter.
Upvotes: 0