<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 | 948409.9 Ops/sec |
children | 818353.0 Ops/sec |
firstChild nextSibling | 6057810.5 Ops/sec |
firstElementChild nextElementChild | 6061825.5 Ops/sec |
ChildNodes2 | 2676689.8 Ops/sec |
Benchmark Explanation
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks to compare the performance of different approaches on various browsers and devices.
The provided benchmark definition json represents four test cases:
childNodes
children
firstChild nextSibling
(without optimization)firstElementChild nextElementChild
Options Compared
Each test case compares two or more options for listing children of an HTML element:
childNodes
: traversing the child nodes using forEach()
loop.children
: traversing the children directly using a for...in
loop.firstChild nextSibling
: traversing the first child node and its subsequent siblings using a while
loop.In addition to these options, two optimized versions of firstChild nextSibling
are included:
firstElementChild nextElementSibling
: traversing only the element children using firstElementChild
and nextElementSibling
.ChildNodes2
: a non-standard approach that uses childNodes
to traverse the elements (this is not a recommended or supported method).Pros and Cons of Different Approaches
childNodes
for elements with only child elements. However, it may skip some child nodes if they are not elements.firstChild nextSibling
without optimization.childNodes
to traverse the elements, which can be slower and less reliable than other methods.Library and Special JS Features
The provided benchmark code does not use any libraries or special JavaScript features beyond the standard DOM API.
Other Alternatives
Other alternatives for listing children of an HTML element include:
querySelectorAll()
instead of children
or childNodes
.It's worth noting that the performance differences between these approaches can vary depending on the specific use case and browser being tested. MeasureThat.net provides a useful platform for comparing the performance of different approaches and identifying the most efficient solutions.