<h3 id="data" data-test="text">kipr202 header</h3>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
var element = document.getElementById("data");
var i = 10000;
while (i--) {
var value = element.dataset.test;
}
var element = document.getElementById("data");
var i = 10000;
while (i--) {
var value = element.getAttribute("test");
}
var element = $("#data");
var i = 10000;
while (i--) {
var value = element.data("test");
}
var element = $("#data");
var i = 10000;
while (i--) {
var value = element.attr("data-test");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
dataset | |
getAttribute | |
jQuery .data() | |
jQuery .attr() |
Test name | Executions per second |
---|---|
dataset | 421.2 Ops/sec |
getAttribute | 65235.4 Ops/sec |
jQuery .data() | 197.3 Ops/sec |
jQuery .attr() | 133.3 Ops/sec |
I'll break down the benchmark and explain what's being tested, the pros and cons of different approaches, and other considerations.
Benchmark Overview
The benchmark tests four different ways to access data from an HTML element:
dataset
property ( Modern JavaScript)getAttribute()
method (Legacy JavaScript).data()
method.attr()
methodOptions Compared
The benchmark compares the performance of these four options on a mobile device running Firefox 103 on Android.
dataset
property to access data stored in an HTML element.getAttribute()
): This option uses the legacy JavaScript getAttribute()
method to access data stored in an HTML element..data()
: This option uses jQuery's .data()
method to store and retrieve data associated with an HTML element..attr()
: This option uses jQuery's .attr()
method to access attributes of an HTML element.Pros and Cons
Here are the pros and cons of each approach:
getAttribute()
)dataset
..data()
:.attr()
:Library and Syntax
The benchmark uses jQuery as the library for two of the options ($.data()
and $.attr()
). The other option, dataset
, is a modern JavaScript property that doesn't require any additional libraries or syntax.
Other Considerations
When choosing between these approaches, consider the following factors:
getAttribute()
might be necessary. However, modern approaches like dataset
are generally more efficient and widely supported..attr()
or the dataset
property might be sufficient. For more complex data, consider using a custom solution or a library that provides more advanced features.dataset
are generally faster than legacy methods.Alternatives
If you don't want to use jQuery, here are some alternative solutions:
getAttribute()
(which is similar to dataset
) or even newer APIs like Element.prototype.dataset
(which provides a more flexible way to access and modify dataset attributes)..data()
and $.attr()
.