I was wondering the other day when typing you selectors in jQuery would it make a difference in performance if you specify your selectors very specific or very loosely.
Update 2:
To sum up some other comments here. The answer is it depends.
jQuery's selector engine Sizzle evaluates the selector the same way CSS does: from right to left. So in general it is better to be very specific on the right side and less specific on the left side.
But it also depends on the structure of the HTML and how scattered the elements are that you want find.
So if you have
a
|
...
|
b
-----------------
| |
d d d c c c c c c c c c c c c c c c c c c c
then being more specific is faster $('a b > c')
, because you are reducing the element set early with b > c
and don't have to check the a
inheritance for every c
.
Whereas if you have
a
|
...
|
b
-----------------
| |
e e e e e e e e d d c c c c c c e e e e e e
then $('a c')
would be faster, since the selector is simpler and testing c
for being a child of b
is redundant in this case (of course you could even do $('c')
).
Original answer:
Regardless which one of them is faster, if you have to access an element over and over again, store a reference to it:
var $element = $('#myId .someElement');
$('some other selector').each(function() {
// access $element here
});
The first selector seems to be a bit faster (in Chrome 8).
In newer browsers (that support querySelectorAll
), the difference is probably not as big as in browsers that do not support it.
Update:
I think it mostly depends on how many built-in methods jQuery can use. So assuming querySelector*
is not available, the first selector can be translated to
document.getElementById('myId')[0].getElementsByClassName('someElement')
For the second selector, jQuery would have to additionally check whether an element is indeed a child or not. I.e. there is some more processing involved.