<div><svg id="target" class="target"></svg></div>
const target = document.getElementById('target');
var div = document.createElement('DIV');
div.innerHTML = `<svg id="target" class="something new"></svg>`;
var replacement = div.firstChild;
var i = 1000;
while (i--) {
target.setAttribute('class', 'something new')
}
var i = 1000;
while (i--) {
target.parentNode.replaceChild(replacement, target);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Set Attribute | |
Replace Element |
Test name | Executions per second |
---|---|
Set Attribute | 829.4 Ops/sec |
Replace Element | 451.9 Ops/sec |
I'd be happy to explain the JavaScript microbenchmark on MeasureThat.net.
Benchmark Overview
The benchmark compares two approaches: setting an attribute (Set Attribute
) and replacing an element using replaceChild
((Replace Element
). The goal is to determine which approach is faster.
Test Cases
There are two test cases:
class
attribute of the target
element 1000 times in a loop.var i = 1000;
while (i--) {
target.setAttribute('class', 'something new');
}
target
element with a new child element (replacement
) 1000 times in a loop.var i = 1000;
while (i--) {
target.parentNode.replaceChild(replacement, target);
}
Library Usage
The benchmark uses the DOM
library to interact with the DOM. Specifically, it uses document.getElementById
, createElement
, setAttribute
, and replaceChild
.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax used in this benchmark.
Benchmark Results
The latest results show that:
Pros and Cons of Each Approach
Other Alternatives
In addition to the two approaches mentioned above, other alternatives for setting or replacing element properties include:
target.style.class = 'something new'
).It's worth noting that the choice of approach depends on the specific use case and performance requirements.