jQuery selector optimization

情到浓时终转凉″ 提交于 2020-01-09 12:48:40

问题


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

  1. Could someone explain why the less specific left is faster as a CSS selector?

  2. Is this a Sizzle thing or does the same apply for document.querySelectorAll ?

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!