<h3 id="data" data-test="text" data-id="some-id">Hello world!</h3>
var element = document.querySelector("#data");
const { test, id } = element.dataset;
const testId = test + id;
const test = element.getAttribute('data-test');
const id = element.getAttribute('data-id');
const testId = test + id;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Dataset | |
getAttribute |
Test name | Executions per second |
---|---|
Dataset | 1825425.8 Ops/sec |
getAttribute | 3761129.5 Ops/sec |
Let's break down the provided JSON and benchmark setup to understand what's being tested.
Benchmark Definition
The benchmark is designed to compare three approaches for accessing data attributes in JavaScript:
dataset
property (using the const { test, id } = element.dataset;
syntax)getAttribute
method (using the element.getAttribute('data-test')
and element.getAttribute('data-id')
syntaxes)Options Being Compared
The two options being compared are:
dataset
property (test
and id
accessors) to access data attributesgetAttribute
method to access data attributes (by their attribute name)Pros and Cons of Each Approach
getAttribute
data-
prefix (e.g., data-test
, data-id
)data-
prefixdataset
propertyLibrary Used
The benchmark doesn't explicitly mention any libraries, but it does use HTML and CSS to create an element with a data-test
attribute. However, the dataset
property access is specific to modern browsers (Chrome 80+, Firefox 69+), which may not be compatible with older versions.
Special JS Feature or Syntax
The benchmark uses ES6 syntax features, such as:
const { test, id } = element.dataset;
)const { test, id } = element.dataset;
)These features are widely supported in modern browsers and Node.js environments.
Alternative Approaches
Other approaches to accessing data attributes could include:
element
object to access data attributes_data-test_
)