<div id="foo" data-episode="000000000" data-show="111111111"></div>
window.x = {
episode: "000000000",
show: "111111111"
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.getAttribute("data-episode");
element.getAttribute("data-show");
}
var element = document.getElementById("foo");
var cachedAttrs = element.attributes;
var i = 1000;
while (i--) {
cachedAttrs["data-episode"].value;
cachedAttrs["data-show"].value;
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.dataset.episode;
element.dataset.show;
}
var i = 1000;
while (i--) {
x.episode;
x.show;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getAttribute | |
attributes | |
dataset | |
js map |
Test name | Executions per second |
---|---|
getAttribute | 22785.5 Ops/sec |
attributes | 8548.9 Ops/sec |
dataset | 9128.2 Ops/sec |
js map | 559283.5 Ops/sec |
The provided benchmark tests various methods to access HTML element data attributes in JavaScript. These methods differ in their approaches, performance, and usability. Here’s a breakdown of the tests, libraries (if any are used), and alternatives.
getAttribute
method to access data-*
attributes from the DOM element.attributes
property of the element directly.dataset
property, which simplifies access to the data-*
attributes in a more JavaScript-friendly way.getAttribute:
data-*
.data-*
attributes.attributes:
data-*
.getAttribute
, as it still accesses the DOM.dataset:
data-*
attributes.data-*
attributes only.js map:
dataset
is the ideal choice. For occasional access or non-data attributes, getAttribute
or attributes
might be appropriate..data()
can simplify the interaction with data-*
attributes and handle browser quirks.In summary, the benchmark effectively demonstrates the performance implications of different techniques for accessing element data, highlighting how traditional DOM interactions can be slower compared to native JavaScript object access. The method chosen should align with performance needs, readability, and specific use cases in application development.