<div id='xd' data-name="xD"></div>
var e = (() => {
const state = {
name: 'xD'
}
const el = document.getElementById('xd')
el.get_name = () => state.name
return el
})()
const name = e.dataset.name
const name = e.get_name()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
by data attribute | |
by function |
Test name | Executions per second |
---|---|
by data attribute | 7390529.5 Ops/sec |
by function | 628602944.0 Ops/sec |
Let's dive into the explanation of the provided JavaScript microbenchmark.
What is being tested?
The benchmark measures the performance difference between two approaches to access a value stored in a HTML element: by using a data attribute (via dataset
) and by accessing a custom function that returns the same value.
Options compared
Two options are being compared:
dataset
property of an HTML element to access the value stored in the data-name
attribute.get_name()
that is defined on the same HTML element.Pros and Cons
Other considerations
The benchmark also considers the impact of using const
to declare variables and the use of arrow functions (as seen in the script preparation code).
Library used (if applicable)
None is explicitly mentioned in the provided benchmark definition. However, it's worth noting that some browsers may have optimized their internal data structures or caching mechanisms for elements with a specific attribute, such as data-
attributes.
Special JS feature or syntax
This benchmark does not use any special JavaScript features or syntax beyond what is typically available in modern browsers. It relies on standard HTML attributes and basic JavaScript functionality.
Alternatives
There are other approaches to access values stored in HTML elements:
getAttribute()
and setAttribute()
: This method is more verbose but allows for more control over the attribute's value.requestAnimationFrame()
or setTimeout()
: These methods can be used to defer execution of code until a specific time, potentially improving performance by avoiding unnecessary computations.Keep in mind that these alternatives might not provide significant performance benefits in this particular benchmark and may introduce additional complexity.