<div id="data" data-test="text">some text</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
$(document).ready(function() {
$("h3#data").data("test");
});
$(document).ready(function() {
$("h3#data").attr("data-test");
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery .data() | |
jQuery .attr() |
Test name | Executions per second |
---|---|
jQuery .data() | 26541.7 Ops/sec |
jQuery .attr() | 26642.8 Ops/sec |
I'd be happy to help explain the benchmark.
What is being tested?
The provided benchmark tests two different approaches for setting and getting data attributes on HTML elements using jQuery: .data()
and .attr()
. The test creates an HTML element with a data-test
attribute, and then uses jQuery to set this attribute using both methods. The benchmark measures the execution time of each method.
Options being compared
The two options being compared are:
.data()
: A jQuery method that sets and gets custom data attributes on HTML elements..attr()
: A jQuery method that sets and gets attributes on HTML elements, including data attributes.Pros and Cons of each approach:
.data()
: Pros:$().data()
shortcut method..attr()
directly; if you need to access a data attribute from outside a jQuery object, you must use $().data()
..attr()
: Pros:href
or class
, as well as custom data attributes..attr()
directly; if you need to access a value from outside a jQuery object, you can use $().attr()
..data()
for setting and getting large amounts of data, since it requires jQuery to parse and store the attribute value..data()
; attributes set with .attr()
are visible to other scripts that have access to the HTML element.Other considerations:
Library and special features:
The test uses jQuery as the library. jQuery provides several features that make it suitable for this type of benchmarking:
Other alternatives:
If you want to test alternative approaches for setting and getting data attributes on HTML elements, some options include:
.data()
method.However, these alternatives may not provide the same level of encapsulation and convenience as jQuery's .data()
method.