简体   繁体   English

jQuery性能 - 通过data-attr或类选择?

[英]jQuery performance - select by data-attr or by class?

Which is faster and why? 哪个更快,为什么? Selecting div (for plugin needs) by $('div[data-something]') or $('div.something') ? 通过$('div[data-something]')$('div.something')选择div(用于插件需求$('div.something') I lean towards the former since it's "cleaner". 我倾向于前者,因为它“更清洁”。

Based on this SO question I know I shouldn't be using both. 基于这个问题,我知道我不应该同时使用这两个问题。 However I didn't find out whether there is a difference between these. 但是我没有发现它们之间是否存在差异。

In Chrome 16 at least, there is no difference . 至少在Chrome 16中, 没有区别 However, if you make the class selector less specific ( $(".test") for example), it does outperform the other methods: 但是,如果使类选择器不那么具体(例如$(".test") ),它的表现优于其他方法:

在此输入图像描述

That was somewhat unexpected, because as ShankarSangoli mentions, I thought the div.test class selector would be faster. 这有些出乎意料,因为正如ShankarSangoli所提到的,我认为div.test类选择器会更快。

It will vary by browser. 它会因浏览器而异。 Nearly all browsers now support querySelectorAll , and jQuery will use it when it can. 几乎所有的浏览器现在都支持querySelectorAll ,jQuery会querySelectorAll使用它。 querySelectorAll can be used with attribute presence selectors, so if it's there jQuery doesn't have to do the work, it can offload it to the engine. querySelectorAll可以与属性存在选择器一起使用,所以如果它在那里jQuery不必执行工作,它可以将它卸载到引擎。

For older browsers without querySelectorAll , jQuery will obviously have to do more work, but even IE8 has it. 对于没有querySelectorAll旧浏览器,jQuery显然必须做更多工作,但即使IE8也有它。

As with most of these things, your best bet is: 与大多数这些事情一样,您最好的选择是:

  1. Don't worry about it until/unless you see a problem, and 除非你发现问题,否则不要担心,并且

  2. If you see a problem, profile it on the browsers you intend to support and then make an informed decision. 如果您发现问题,请在您打算支持的浏览器上对其进行分析,然后做出明智的决定。

Selecting by class is always faster than attribute selector because jQuery tries to use the native getElementByCalssName first if supported by browsers. 按类选择总是比属性选择器快,因为如果浏览器支持,jQuery会首先尝试使用本机getElementByCalssName If not it uses the querySelector which uses css selectors to find the elements within the page. 如果没有,它使用querySelector ,它使用css选择器来查找页面中的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM