<div id="test-subject" data-test="foo"></div>
function attr(element, attribute, value) {
if (value) {
element.setAttribute(attribute, value);
return;
}
return element.getAttribute(attribute);
}
var test_subject = document.getElementById("test-subject");
var i = 1000;
while (i--) {
attr(test_subject, 'data-test', i);
test_subject.innerHTML = attr(test_subject, 'data-test');
}
var test_subject = document.getElementById("test-subject");
var i = 1000;
while (i--) {
test_subject.setAttribute('data-test', i);
test_subject.innerHTML = test_subject.getAttribute('data-test');
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Shorthand | |
Native |
Test name | Executions per second |
---|---|
Shorthand | 17.4 Ops/sec |
Native | 16.8 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The MeasureThat.net benchmark compares two approaches to setting/getting attributes on an HTML element: a "shorthand" method using JavaScript's setAttribute
and getAttribute
methods in a single call, versus the native way of setting/getting attributes using separate calls for each operation.
Shorthand Method (Test Name: Shorthand)
The shorthand method is defined as follows:
function attr(element, attribute, value) {
if (value) {
element.setAttribute(attribute, value);
return;
}
return element.getAttribute(attribute);
}
var test_subject = document.getElementById("test-subject");
var i = 1000;
while (i--) {
attr(test_subject, 'data-test', i);
test_subject.innerHTML = attr(test_subject, 'data-test');
}
Native Method (Test Name: Native)
The native method is defined as follows:
var test_subject = document.getElementById("test-subject");
var i = 1000;
while (i--) {
test_subject.setAttribute('data-test', i);
test_subject.innerHTML = test_subject.getAttribute('data-test');
}
Comparison
Both methods are executed in a loop, with the attr
function being called with different values for the attribute
and value
parameters. The native method uses separate calls for setting (setAttribute
) and getting (getAttribute
), while the shorthand method combines both operations into a single call.
Pros and Cons of Each Approach
setAttribute
and getAttribute
calls.attr
function.setAttribute
and getAttribute
calls.Library Usage
The benchmark uses the built-in JavaScript document.getElementById()
and HTMLElement.setAttribute()
/HTMLElement.getAttribute()
methods, which are part of the standard DOM API. These methods are widely supported across different browsers and platforms.
Special JS Features or Syntax
This benchmark does not use any special JavaScript features or syntax that would require specific browser support or configuration.
Alternative Approaches
Other approaches to setting/getting attributes on an HTML element might include:
However, these alternatives are not being tested in this specific benchmark.