<html>
<body>
<div id='test'>
<div name='a'></div>
<div name='b'></div>
<div name='c'></div>
</div>
</body>
</html>
var parent = document.getElementById('test');
parent.childNodes.forEach(function (node) {
let n = node;
});
for (let i = 0; i < parent.children.length; i++) {
let n = parent.children[i];
}
let elem = parent.firstChild;
do {
let n = elem;
} while (elem = elem.nextSibling)
let elem = parent.firstElementChild;
do {
let n = elem;
} while (elem = elem.nextElementSibling)
let children = parent.childNodes;
for (let i = 0; i < children.length; i++) {
let n = children[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
childNodes | |
children | |
firstChild nextSibling | |
firstElementChild nextElementChild | |
ChildNodes2 |
Test name | Executions per second |
---|---|
childNodes | 1170831.1 Ops/sec |
children | 1717997.5 Ops/sec |
firstChild nextSibling | 7975128.0 Ops/sec |
firstElementChild nextElementChild | 11051960.0 Ops/sec |
ChildNodes2 | 3174580.8 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Description
The benchmark measures the fastest way to list children of an HTML element in JavaScript. The test compares four different approaches:
forEach
.children
property directly on the parent element.firstElementChild
and nextElementSibling
properties.Options Compared
The options being compared are:
childNodes
, children
)firstChild/nextSibling
, firstElementChild/nextElementSibling
)Pros and Cons
firstChild/nextSibling
, but with more modern browsers that support firstElementChild
.Library and Syntax
There is no specific library being tested in this benchmark. However, the use of modern JavaScript features like arrow functions (=>
) and template literals (\r\n\r\n
) suggests that the test is designed to run on a relatively recent browser.
Special JS Features or Syntax
The test doesn't use any special JavaScript features or syntax beyond what's mentioned above (arrow functions, template literals). If you're curious about other modern features like async/await, let me know!
Alternatives
Other alternatives for listing children of an HTML element include:
children()
method.Keep in mind that these alternatives might not provide the same level of performance as the options being compared in this benchmark.