jQuery 选择器优化
在选择器的右侧要具体,而在左侧则不太具体。
// unoptimized
$('div.data .gonzalez');
// optimized
$('.data td.gonzalez');
有人可以解释一下为什么不太具体的左侧作为 CSS 选择器更快吗?
这是 Sizzle 的事情还是同样适用于
document.querySelectorAll
?在 CSS 文件中使用“类似优化”的 CSS 选择器是否会带来速度提升?
Be specific on the right-hand side of your selector, and less specific on the left.
// unoptimized
$('div.data .gonzalez');
// optimized
$('.data td.gonzalez');
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
jQuery 的 Sizzle 引擎从右到左解析选择器,所以这是真的。但也有例外,例如当第一个操作数是 ID 时。然后搜索将在具有该 ID 的元素的上下文中进行。这是 Sizzle 引擎的特殊性,但我不知道 querySelectorForAll 是如何实现的。
示例:
Sizzle 将获取具有类 gonzalez 的所有 DOM 元素,然后检查每个元素的祖先是否是具有类数据的 div 标签
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:
Sizzle will get all the DOM elements with class gonzalez then check for each if an ancestor is a div tag with class data
这本书顺便提到了这一点,但我相当确定该建议是特定于 Sizzle(jQuery 选择器引擎)的,而不是普遍的。您的情况可能会有所不同,但实现
querySelectorAll
的浏览器不太可能显示现实世界的差异。Sizzle 在适当的时候从内到外工作,因此可能会查找 td.gonzales,然后查看它是否在 .data 内,而不是相反。我记得当 Sizzle 刚推出时,这有点令人惊讶,但实际上效果更好。因此您可以明白为什么后代选择器的右侧越具体越好。
这是一个测试用例,在 IE7 中尝试一下,您会看到一个标记的首选项更具体的右侧。但在现代浏览器中尝试一下,你会发现基本上没有什么区别。
不过,这都是微观优化,在没有实际问题需要解决的情况下几乎毫无用处,因为它会根据页面上的元素而发生巨大变化。记住,如果您实际上有一个缓慢的选择器,可能会给您在旧浏览器上带来麻烦,但除此之外......
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...