<html>
<body>
<div id='test'>
<div class='item' id='a' name='a'>a</div>
<div class='item' id='b' name='b'>b</div>
<div class='item' id='c' name='c'>c</div>
</div>
</body>
</html>
var parent = document.getElementById('test');
var store = [];
parent.childNodes.forEach(function (node) {
if ( node.nodeName !== '#text') {
store.push( { name: node.attributes.name.value } );
}
});
let elem = parent.firstElementChild;
do {
elem.setAttribute('name','d');
} while (elem = elem.nextElementSibling)
for (let i = 0; i < store.length; i++) {
store[i].name = 'd';
}
let elem = parent.firstElementChild;
do {
elem.attributes.name.value = 'd';
} while (elem = elem.nextElementSibling)
let elem = parent.firstElementChild;
do {
elem.nodeValue = 'd';
} while (elem = elem.nextElementSibling)
let elem = parent.firstElementChild;
do {
elem.textContent = 'd';
} while (elem = elem.nextElementSibling)
for (let i = 0; i < store.length; i++) {
store[i] = {name:'d'};
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
fastest iter childelements + setAttribute | |
Array item | |
fastest iter childelements + attributes | |
fastest iter childelements + nodeValue | |
fastest iter childelements + textContent | |
Array object |
Test name | Executions per second |
---|---|
fastest iter childelements + setAttribute | 513185.2 Ops/sec |
Array item | 2043916.4 Ops/sec |
fastest iter childelements + attributes | 559170.4 Ops/sec |
fastest iter childelements + nodeValue | 2433263.2 Ops/sec |
fastest iter childelements + textContent | 1598468.4 Ops/sec |
Array object | 1988372.6 Ops/sec |
Let's dive into the benchmark.
Benchmark Description The benchmark measures the performance of different approaches to setting attributes on DOM elements and arrays.
There are four main approaches being compared:
nodeValue
property of a DOM element directly, without creating a separate attribute object.setAttribute
method to set an attribute on a DOM element's attributes collection.name
property.Pros and Cons of each approach:
Array item
approach but creates an immutable object that cannot be modified directly.Library usage None of the provided benchmark definitions rely on external libraries.
Special JS features or syntax The benchmark utilizes modern JavaScript features such as:
parent.childNodes.forEach
and store[i].name = 'd'
.Alternative approaches Other possible approaches to setting attributes on DOM elements or arrays could include:
DOMStringFactory
API: Some modern browsers provide a DOMStringFactory
class that can help optimize attribute creation and modification.Keep in mind that these alternative approaches may have varying degrees of compatibility across different browsers and versions, so it's essential to test their performance in your specific use case.