<div id="foo" data-foo="foo_id"></div>
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
var foo = element.getAttribute("data-foo");
}
var i = 10000;
while (i--) {
var foo = element.dataset.foo;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getAttribute | |
dataset |
Test name | Executions per second |
---|---|
getAttribute | 3030.6 Ops/sec |
dataset | 1214.3 Ops/sec |
Let's break down the provided benchmark JSON and analyze what's being tested.
Benchmark Purpose:
MeasureThat.net is testing two approaches for accessing data attributes in HTML elements:
setAttribute
: A method to set the value of an attribute on an element..dataset
property: A read-only property that returns a dictionary-like object containing the element's attributes, including data attributes.Options Compared:
The benchmark compares the performance of using setAttribute
versus accessing data attributes through the .dataset
property. These two approaches have different implications for code readability, maintenance, and potential security concerns.
Pros and Cons of Each Approach:
setAttribute
:
Pros:
Cons:
setAttribute
with untrusted input)..dataset
property..dataset
:
Pros:
Cons:
.dataset
involves creating a dictionary-like object..dataset
property correctly (e.g., older versions of Internet Explorer).Library Used:
In this benchmark, no specific library is required to access .dataset
, as it's a built-in property of HTML elements. However, some libraries might provide additional functionality or polyfills for older browsers that don't support .dataset
.
Special JS Feature/Syntax:
The benchmark uses the while
loop with a decrementing variable (i--
) and an immediate invoked function expression (IIFE) to execute the test code. This is a standard JavaScript syntax, but it's worth noting that some modern engines might optimize or rewrite such constructs for better performance.
Alternative Approaches:
Other alternatives to accessing data attributes could include:
getAttribute
with a specific attribute name (e.g., element.getAttribute('data-foo')
) instead of the .dataset
property.Keep in mind that each approach has its trade-offs, and the choice ultimately depends on the specific requirements of your application.