问题
Be specific on the right-hand side of your selector, and less specific on the left.
// unoptimized
$('div.data .gonzalez');
// optimized
$('.data td.gonzalez');
Quote Source
Could someone explain why the less specific left is faster as a CSS selector?
Is this a Sizzle thing or does the same apply for
document.querySelectorAll
?Are there any speed gains using "similarly optimised" CSS selectors in CSS files?
回答1:
jQuery's Sizzle Engine parse selectors from right to left, so it's true. There are exceptions though, for example when the first operand is an ID. Then the search will operate in the context of the element with this ID. That's a particularity of the Sizzle Engine, but I don't know how querySelectorForAll is implemented.
An example:
$('div.data .gonzalez');
Sizzle will get all the DOM elements with class gonzalez then check for each if an ancestor is a div tag with class data
回答2:
The book sort of mentions this in passing, but I'm fairly certain that advice is specific to Sizzle (the jQuery selector engine), not generally. Your mileage may vary, but a browser that implements querySelectorAll
is unlikely to show a real-world difference.
Sizzle works inside-out when appropriate, and so may look for td.gonzales
and then look to see if it's within a .data
, rather than the other way around. I remember when Sizzle first came out, this was a bit of a surprise, but it actually worked out better. So you can see why the more specific the right-hand side of the descendant selector, the better.
Here's a test case, try that in IE7 and you'll see a marked preference for the more specific right-hand side. But try it in a modern browser and you should seem basically no difference.
This is all micro-optimization, though, and pretty much useless in the absence of a real-world problem to solve, because it varies dramatically based on the elements on your page. Useful to remember if you actually have a slow selector causing you trouble on older browsers, perhaps, but other than that...
来源:https://stackoverflow.com/questions/6028555/jquery-selector-optimization