A few months ago this article pointed out that classes could actually be avoided all together from website development.
My question is, how efficient are the data selectors compared to class selectors?
A simple example would be to compare querying for elements with
data-component='something' versus elements with
class='class1 class2 something anotherClass'.
[data-<attr>='<value>'] selector will check the value as a whole versus the class string that should be split. With this in mind, data atributes should be faster.
jQuery("[data-component='something']") be more efficient than
I wouldn't call it conclusive, but it does appear class selectors are faster... I just put this together for a quickie test.
Based on Vlad's and my jsperf tests... if performance is a concern (especially IE)... classes are still the way to go
After checking out BLSully's answer and the test page he provided, here are the actual figures for comparison.
jQuery class selector performance vs jQuery data attribute selector performance operations per second:
I have the impression that the performance of the selectors are fast enough right now even in the mobile browsers out there. Unless you really plan to use selectors a lot, data-attributes or class based, (in which case I would suggest to revisit your code to try to cache the already queried selectors) we can consider them not that bad. And I would even say that is not dramatic to use style over the others.
I think browsers vendors have spent more time improving the most used scenario (query against classes) than querying against selectors. This is changing and I would not be surprised if they start optimizing other cases too.
I don't know about all this answers but i ran my own test and attribute are faster.
you can try it your self just save the time at the beginning, do the task and get the final time then do the math
var newDate = new Date().getTime(); $('.test-t').removeClass('act'); $('.t1r').addClass('act'); var currentDate = new Date().getTime(); var diff = currentDate-newDate; console.log(diff); var newDate = new Date().getTime(); $('.test-t2').attr('this-act',''); $('.t2r').attr('this-act','1'); var currentDate = new Date().getTime(); var diff = currentDate-newDate; console.log(diff);
©2020 All rights reserved.