Why can I select an element by class faster than the data attribute?

I made a little jsperf to test element selection using jQuery: http://jsperf.com/testing-class-selector-vs-data-selector2

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

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

      

against

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

      

Shouldn't they be just as effective? Are both looking for an exact string match within a specific DOM region, either in "class" or "data-ui"?

+3


source to share


1 answer


it

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

      

scans the whole DOM tree, but this



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

      

simply returns a list of the elements of this class. Usually browsers support collecting elements under each class. For optimization purposes. This assembly is populated once per DOM parsing (and updating class attributes).

+3


source







All Articles