<ul>
</ul>
<ol>
</ol>
const ul = document.querySelector('ul');
const ol = document.querySelector('ul');
for (let i = 0; i < 1000; i++) {
const li = document.createElement('li')
li.classList.add(i % 2 === 0 ? 'even' : 'odd')
ul.appendChild(document.createElement('li'));
ol.appendChild(document.createElement('li'));
}
var oddListItems = document.querySelectorAll('li.odd');
var anything = [];
for (const item of oddListItems) {
anything.push(item);
}
Array.from(oddListItems).forEach(item => anything.push(item));
oddListItems.forEach(item => anything.push(item));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for ... of | |
Array.from | |
NodeList.forEach |
Test name | Executions per second |
---|---|
for ... of | 56175100.0 Ops/sec |
Array.from | 22263000.0 Ops/sec |
NodeList.forEach | 97272792.0 Ops/sec |
The benchmark identified as "NodeList loop iterator comparison v2" evaluates the performance of different methods for iterating over a NodeList in JavaScript. The NodeList is created by querying for all <li>
elements that have the class "odd" within the previously defined <ul>
and <ol>
structures. The benchmark consists of three test cases, each testing a different method of iteration.
for...of Loop
for (const item of oddListItems) {
anything.push(item);
}
for...of
can be slower compared to traditional loops, but this has improved significantly with modern JavaScript engines.Array.from with forEach
Array.from(oddListItems).forEach(item => anything.push(item));
forEach
. It enhances compatibility with array manipulation functions.NodeList.forEach
oddListItems.forEach(item => anything.push(item));
forEach
method on the NodeList, making it concise and efficient, as no conversion is needed. It maintains the semantic clarity of the operation.forEach
method on NodeLists.The benchmark results show that NodeList.forEach
yielded the highest performance, achieving around 97 million executions per second, followed by the for...of
loop at about 56 million, and finally Array.from
at approximately 22 million. This indicates a clear preference for using the native forEach
method in terms of speed for this specific case.
forEach
on NodeLists, while for...of
and Array.from
provide broader compatibility, although for...of
support has also been widely adopted in modern browsers.for
loop to iterate through a NodeList is another alternative, which can be optimized for performance in many JavaScript environments:for (let i = 0; i < oddListItems.length; i++) {
anything.push(oddListItems[i]);
}
Array.from(oddListItems).map(...)
could be another choice, though it adds the overhead of creating a new array:Array.from(oddListItems).map(item => anything.push(item));
In conclusion, the test compares three distinct methods of iterating over a NodeList, highlighting both performance and usability. Each approach has its strengths and trade-offs, so the "best" method may vary depending on particular project requirements and target browser environments.