Are data attribute css selectors faster than class selectors?

前端 未结 4 1531
眼角桃花
眼角桃花 2020-12-01 04:32

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 s

相关标签:
4条回答
  • 2020-12-01 04:47

    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.

    0 讨论(0)
  • 2020-12-01 04:48

    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

    0 讨论(0)
  • 2020-12-01 04:50

    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
    0 讨论(0)
  • 2020-12-01 05:08

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

    0 讨论(0)
提交回复
热议问题