简体   繁体   中英

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') ? 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 . However, if you make the class selector less specific ( $(".test") for example), it does outperform the other methods:

在此输入图像描述

That was somewhat unexpected, because as ShankarSangoli mentions, I thought the div.test class selector would be faster.

It will vary by browser. Nearly all browsers now support querySelectorAll , and jQuery will use it when it can. 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.

For older browsers without querySelectorAll , jQuery will obviously have to do more work, but even IE8 has it.

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. If not it uses the querySelector which uses css selectors to find the elements within the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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