<div id="foo" data-foo="foo_id"></div>
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
var foo = element.getAttribute("data-foo");
}
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
var foo = element.dataset.foo;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getAttribute | |
dataset |
Test name | Executions per second |
---|---|
getAttribute | 3911.0 Ops/sec |
dataset | 1719.1 Ops/sec |
Let's break down the benchmark and its options.
Benchmark Overview
The benchmark compares two ways to access data attributes in HTML elements: getAttribute
and dataset
. The goal is to determine which method is faster.
Script Preparation Code
There is no script preparation code provided for this benchmark. This means that the test starts with a clean slate, without any additional JavaScript code that might affect the results.
HTML Preparation Code
The HTML preparation code creates a simple element with a data-foo
attribute:
<div id="foo" data-foo="foo_id"></div>
This element will be used to test both getAttribute
and dataset
.
Individual Test Cases
There are two test cases:
getAttribute
: This test case uses the getAttribute
method to access the data-foo
attribute. The benchmark defines a while loop that iterates 10,000 times, accessing the attribute on each iteration.dataset
: This test case uses the dataset
property to access the same data-foo
attribute. Again, the benchmark defines a while loop that iterates 10,000 times, accessing the attribute on each iteration.Pros and Cons of Each Approach
getAttribute
:dataset
for large datasets, as it involves parsing the attribute string.dataset
:Library/Technique Used
In this benchmark, no libraries or techniques beyond standard JavaScript are used. The dataset
property is a built-in feature of the DOM API.
Special JS Features/Syntax
None mentioned explicitly. However, it's worth noting that some older browsers may not support the dataset
property or have slightly different behavior when using getAttribute
.
Other Alternatives
If you want to compare other methods for accessing data attributes in HTML elements, you could consider:
.attr()
).