<div id="foo" data-foo></div>
var element = document.getElementById("foo");
var foo = element.hasAttribute("data-foo");
var foo = "foo" in element.dataset;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
hasAttribute | |
dataset |
Test name | Executions per second |
---|---|
hasAttribute | 13103964.0 Ops/sec |
dataset | 4008161.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is being tested?
The benchmark compares two ways to check if an element has a specific attribute or data property: hasAttribute
and in dataset
. Specifically, it tests whether element.hasAttribute("data-foo")
is faster than element["dataset"] == "foo"
(or simply "foo" in element.dataset
) for the case where the element has a data-foo
attribute.
Options compared:
There are two options being compared:
getAttribute()
method and checking if the returned value is truthy.in
operator to check if a property exists in the dataset
object of an element.Pros and Cons:
getAttribute()
must be called and then checked for truthiness.hasAttribute
, as it only requires a single property access and does not require an extra call to getAttribute()
.dataset
object or its syntax.Other considerations:
element
object, which is likely part of the DOM API. In this case, no library is explicitly used.Alternatives:
If you're interested in testing other methods for checking attributes or data properties, you could consider adding new benchmark definitions with the following alternatives:
element.getAttribute("data-foo") === "foo"
instead of hasAttribute
Object.prototype.hasOwnProperty.call(element.dataset, "foo")
instead of in dataset
get()
method or a custom implementation for attribute checkingKeep in mind that these alternatives might have different performance characteristics and may require additional setup or modifications to the benchmark.