I just noticed that adding context to the selector is much faster than refining your selector.
$('li',$('#bar')).append('bla');
Is twice as faster than:
$('#bar li').append('bla');
Is this generally true?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is true in the general case. With respect to your specific examples however it is not necessarily true for jQuery <= 1.2.6.
Up to and including jQuery 1.2.6 the selector engine worked in a ‘top down’ (or ‘left to right’) manner. Meaning that both your examples would operate like this (roughly):
jQuery 1.3.x (ie, Sizzle, which jQuery embeds) introduced a ‘bottom up’ (or ‘right to left’) approach to querying the DOM. So
$('#bar li')now becomes (roughly):There are benefits and downsides to both approaches. You found one of the downsides.
Edit: just found out from this discussion that Sizzle trunk now makes a special exemption of selectors where
#idis first. It uses that as the root context, speeding things up a bit. This should diminish if not eliminate the speed differences you are seeing.