简体   繁体   中英

Why am I able to select an element by class more quickly than by data-attribute?

I made a small jsperf to test selecting an element with jQuery: http://jsperf.com/testing-class-selector-vs-data-selector2

I found the results to be shocking. It says that it is 80% slower to use:

var foo = $('[data-ui=foo]');

versus

var foo = $('.ui-foo');

Shouldn't these be equally as performant? Both looking for an exact match on a string inside of a specific area of the DOM either in 'class' or 'data-ui'?

This

var foo = $('[data-ui=foo]');

scans the whole DOM tree but this

var foo = $('.ui-foo');

simply returns list of elements of that class. Usually browsers maintain collection of elements under each class. For optimization purposes.This collection gets populated once per DOM parsing time (and class attribute updates).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM