<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>
window.onload = function() {
document.querySelector("h3#data").dataset.test;
}
window.onload = function() {
document.querySelector("h3#data").getAttribute("data-test");
}
$(document).ready(function() {
$("h3#data").data("test");
});
$(document).ready(function() {
$("h3#data").attr("data-test");
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
dataset | |
getAttribute | |
jQuery .data() | |
jQuery .attr() |
Test name | Executions per second |
---|---|
dataset | 668620.4 Ops/sec |
getAttribute | 720647.4 Ops/sec |
jQuery .data() | 17780.6 Ops/sec |
jQuery .attr() | 18842.4 Ops/sec |
Let's dive into the provided benchmark JSON and explain what is tested, compared, and their pros and cons.
Benchmark Overview
The benchmark tests four different approaches to retrieve data from an HTML element:
dataset
(modern JavaScript way)getAttribute
(legacy DOM method)jQuery .data()
(JQuery's custom attribute storage)jQuery .attr()
(JQuery's attribute retrieval method)Options Compared
Each option is compared to measure their performance, specifically the number of executions per second.
Pros and Cons of Each Approach
dataset
: This approach uses modern JavaScript's dataset
property to store custom attributes on an element. It's a convenient way to store data that doesn't require serialization or deserialization.getAttribute
: This legacy DOM method retrieves the value of an attribute using its name as a string.jQuery .data()
: This is JQuery's custom attribute storage mechanism that stores data on an element under the data-
prefix.jQuery .attr()
: This method retrieves the value of an attribute using its name as a string.Library Usage
jQuery
is used in options 3 and 4. It's a JavaScript library that provides additional functionality for DOM manipulation and event handling.Special JS Feature or Syntax
None of the options use special JavaScript features or syntax beyond the basics of retrieving attribute values.
Other Alternatives
If you need to retrieve data from an HTML element, other alternatives include:
data-attribute-name
) and accessing them using modern JavaScript methods like dataset
or getAttribute
.Keep in mind that the choice of approach depends on your specific use case, target browser support, and performance requirements.