<h3 id="data" data-test="text">Some test content</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>
window.onload = function() {
var test = document.querySelector("h3#data").dataset.test;
document.querySelector("h3#data").dataset.test = test+"1";
}
window.onload = function() {
var test = document.querySelector("h3#data").getAttribute("test");
document.querySelector("h3#data").setAttribute("test", test+"1");
}
$(document).ready(function() {
var $h3 = $("h3#data");
var test = $h3.data("test");
$h3.data("test", test+"1");
});
$(document).ready(function() {
var $h3 = $("h3#data");
var test = $h3.attr("data-test");
$h3.attr("data-test", test+"1");
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
dataset | |
getAttribute | |
jQuery .data() | |
jQuery .attr() |
Test name | Executions per second |
---|---|
dataset | 1207225.4 Ops/sec |
getAttribute | 1055182.4 Ops/sec |
jQuery .data() | 38456.8 Ops/sec |
jQuery .attr() | 31455.0 Ops/sec |
Benchmark Overview
The MeasureThat.net benchmark compares the performance of three approaches to update and retrieve data attribute values in HTML elements: dataset
, getAttribute()
, jQuery.data()
, and jQuery.attr()
.
Test Cases
Each test case is designed to measure the execution time of a specific approach:
dataset
: Retrieves and updates the value of a dataset attribute using the dot notation (test.dataset.test
) and assignment (test.dataset.test = test + "1"
).getAttribute()
: Uses the getAttribute()
method to retrieve and update the value of an attribute with the specified name ("test"
).jQuery.data()
: Utilizes jQuery's .data()
method to store and retrieve data associated with an element, using a key-value pair ("test"
, "value"
).jQuery.attr()
: Employs jQuery's .attr()
method to access and modify attribute values.Comparison Options
The benchmark compares the performance of each approach across different browsers (Chrome 127) on desktop devices running Windows operating systems.
Pros and Cons
dataset
:getAttribute()
:dataset
.jQuery.data()
:dataset
.jQuery.attr()
:Library and Syntax
The benchmark uses the jQuery library (version 3.5.1) to utilize .data()
and .attr()
methods.
There are no special JavaScript features or syntax used in this benchmark that would require advanced knowledge of JavaScript to understand.
Other Alternatives
If you need an alternative approach, consider:
DOMTokenList
: A modern API for working with HTML attributes. It's faster than getAttribute()
and attr()
, but might not be supported in older browsers.MutationObserver
: An API for observing changes to the DOM. It can be used to detect attribute changes, but its performance characteristics depend on browser support.Keep in mind that these alternatives may require additional setup or library inclusion.