<div id="foo" data-foo="foo_id"></div>
var element = document.getElementById("foo");
var foo = element.getAttribute("data-foo");
var element = document.getElementById("foo");
var foo = element.dataset.foo;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getAttribute | |
dataset |
Test name | Executions per second |
---|---|
getAttribute | 19856152.0 Ops/sec |
dataset | 12311116.0 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The benchmark is designed to compare two approaches for accessing data in HTML elements: getAttribute
and dataset
. The script preparation code is empty, which means that the JavaScript code will be run on a clean slate. The HTML preparation code creates a simple <div>
element with an ID "foo" and a data-foo
attribute set to "foo_id".
Individual Test Cases
There are two test cases:
getAttribute
The benchmark definition is:var element = document.getElementById("foo");
var foo = element.getAttribute("data-foo");
This test case uses the getAttribute
method to access the value of the data-foo
attribute on the foo
element.
dataset
The benchmark definition is:var element = document.getElementById("foo");
var foo = element.dataset.foo;
This test case uses the dataset
property to access the value of the foo
attribute on the foo
element.
Options Compared
The two approaches are compared in terms of performance and speed. The benchmark measures how many executions per second (ExecutionsPerSecond) each approach can handle.
Pros and Cons
getAttribute
because it doesn't require an extra lookups.Library and Purpose
Neither of these methods rely on any external libraries, but they do utilize the DOM (Document Object Model) API, which is a fundamental part of JavaScript programming.
Special JS Feature or Syntax
This benchmark uses a feature that's specific to modern browsers: dataset
. The dataset
property is not supported in older browsers like Internet Explorer. This means that if you're targeting older browsers, you may need to use the getAttribute
method instead.
Other Alternatives
If you needed to access attributes on an element without using getAttribute
or dataset
, you might consider other approaches:
data()
method.However, these alternatives are less common and may not be as performant as using the built-in getAttribute
or dataset
methods.