Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 796
mreq Avatar asked Feb 07 '12 18:02

mreq


3 Answers

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:

enter image description here

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

like image 161
James Allardice Avatar answered Oct 24 '22 18:10

James Allardice


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.

like image 26
T.J. Crowder Avatar answered Oct 24 '22 19:10

T.J. Crowder


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.

like image 32
ShankarSangoli Avatar answered Oct 24 '22 18:10

ShankarSangoli