<div id="div" data-foo="foo" data-bar="bar" data-baz="baz" data-test-a="a" data-test-b="b" data-test-c="c">
let div = document.getElementById('div');
Object.keys(div.dataset).filter(v => v.startsWith('test')).map(v => v.substring(4).toLowerCase());
Array.from(div.attributes).map(a => a.nodeName).filter(v => v.startsWith('data-test-')).map(v => v.substring(10));
let l = []; for(var i=0; i < div.attributes.length; i++) { let n = div.attributes[i].nodeName; if(n.startsWith('data-test-')) l.push(n.substring(10)); }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.keys() + .dataset | |
Array.from() + .attributes | |
for + .attributes |
Test name | Executions per second |
---|---|
Object.keys() + .dataset | 955685.9 Ops/sec |
Array.from() + .attributes | 794734.0 Ops/sec |
for + .attributes | 1026422.6 Ops/sec |
The benchmark presented tests various methods of iterating over and filtering data-* attributes in a DOM element (a <div>
in this case). The focus is on performance comparisons among three different approaches: using Object.keys()
with the .dataset
property, using Array.from()
with .attributes
, and using a traditional for
loop with .attributes
.
Object.keys() + .dataset
Object.keys()
to retrieve the keys of the dataset
, filters them to only include those that start with "test", and then transforms the keys by removing the "test-" prefix and converting them to lowercase.dataset
, making it potentially more straightforward for data attributes defined in HTML.Array.from() + .attributes
attributes
collection (a live collection) to an array using Array.from()
, filters for attributes that start with "data-test-", and then transforms them by removing the "data-test-" prefix.data-*
convention or if you want to inspect all attributes.for + .attributes
attributes
collection, checks each attribute's name, and if it starts with "data-test-", it pushes the value (minus the prefix) into a new array.The benchmark results indicate that the for + .attributes
method is the most performant, achieving an execution rate of approximately 1,026,423 executions per second. In comparison, the Object.keys() + .dataset
method performed at around 955,686 executions per second, and Array.from() + .attributes
was slightly slower at around 794,734 executions per second.
for
loop) might be justified.Beyond the methods tested, there are several other approaches one could consider:
forEach
or map
directly on NodeList
: The NodeList
returned by querySelectorAll()
can be used with forEach
, though it may still require additional handling to filter and transform.Understanding the context and requirements is critical when choosing the appropriate method for performance and maintainability in JavaScript operations.