Are data attribute css selectors faster than class selectors?

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'.

The [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.

So, to refine the question, in the case of CSS, are we better off with class selector or data selector? And from a javascript point of view, will jQuery("[data-component='something']") be more efficient than jQuery(".something")?

Answers:

Answer

I wouldn't call it conclusive, but it does appear class selectors are faster... I just put this together for a quickie test.

http://jsperf.com/data-selector-performance

EDIT:

Based on Vlad's and my jsperf tests... if performance is a concern (especially IE)... classes are still the way to go

Answer

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:

  • 31% faster in Chrome 27.0.1453
  • 140% faster in Firefox 15.0.1
  • 131% faster in Firefox 21.0
  • 1,267% faster in IE 9.0
  • 1,356% faster in IE 10.0
Answer

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.

Answer

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);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.