<div id="foo" class="foo bar bazzer" data-foo="foo_id" data-bar="bar_id" data-bazzer="bazzer_id"></div>
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
var foo = Object.fromEntries([element.attributes].filter(({ name }) => name.startsWith("data-")).map(({ name, value }) => ([name.slice(5), value])));
}
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
var foo = { element.dataset };
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
attributes | |
dataset |
Test name | Executions per second |
---|---|
attributes | 125.4 Ops/sec |
dataset | 88.3 Ops/sec |
In this benchmark, two different approaches for accessing HTML element data attributes are compared. The goal is to measure the performance of using the dataset
property versus filtering through the attributes
collection of an HTML element. Here's a detailed breakdown of each approach:
Using attributes
:
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
var foo = Object.fromEntries([...element.attributes].filter(({ name }) => name.startsWith("data-")).map(({ name, value }) => ([name.slice(5), value])));
}
attributes
collection of the element with the ID "foo". It filters this collection to find attributes that start with "data-", then transforms these attributes into an object where the keys are the attribute names (stripped of the 'data-' prefix) and the values are the attributes' respective values.attributes
collection, filtering it, and then mapping it into an object.Using dataset
:
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
var foo = { ...element.dataset };
}
element
's dataset
into a new object using the spread operator.attributes
approach if modifications or custom handling of normal attributes is needed.According to the results:
attributes
test runs at approximately 125.4 executions per second.dataset
test runs at approximately 88.3 executions per second.The benchmark shows that the attributes
approach outperformed the dataset
approach in this specific case. This might be counterintuitive given the general expectations regarding the performance of accessing the dataset
property directly. The performance difference can be attributed to how quickly JavaScript engines optimize for certain patterns and, in some cases, the characteristics of the environment, as well as how the benchmark was set up (for instance, the number of iterations).
In conclusion, the choice of approach should take into account the specific context of how attributes will be used, and it generally pays to benchmark different solutions if performance is a critical factor.