Reputation: 7715
I was just wondering if there is a reason why I should prefer this
<div class="identifying-class">bla bla</div>
<div class="identifying-class">bla bla</div>
var interestingElements = $("div.identifying-class);
over this
<div data-identifying-attr="true">bla bla</div>
<div data-identifying-attr="true">bla bla</div>
var interestingElements = $("div[data-identifying-attr]");
Are attribute based selectors quicker /slower/the same speed as class based selectors? Is one method deemed better practice than the other - if so why?
Upvotes: 3
Views: 85
Reputation: 165951
The class selector will be faster (in modern browsers with getElementsByClassName
anyway, and quite likely in older ones too). Here's the results of a quick test:
Note that I've only run that on Chrome 15. Other browsers may differ slightly but the outcome should be similar. Also note that in the real world this is highly unlikely to make any difference to performance. The difference between the 2 is only 19% (despite the fact it looks like a big difference on the graph).
Upvotes: 3
Reputation: 719
My 2c:
With today's super high speed and memory bloaded workstations (a.k.a. personal computers), nanoseconds in performance difference is no longer an issue. So, assumed (I have never used the data-identifying-attr) both solutions work, it is up to the coder which one to use.
I am all for "self-identiting" where the more I code with a personal touch, the better I feel. I do my best to make my code understood by anyone but will have a personal touch and, if there are any variations in solutions where my personal touch can be implemented, I'll do so!
Upvotes: 1
Reputation: 3721
There's no significant performance issue about this. But class="identifying-class"
is more readable. You can dig deeper at http://sizzlejs.com/. Sizzle is the css selector engine used by jQuery.
Upvotes: 3