<ul>
</ul>
var ul = document.querySelector('ul');
for(var i=0;i<1000;i++) {
ul.appendChild(document.createElement('li'));
}
var listItems = document.querySelectorAll('li');
var other = Array.from(listItems);
var other = [listItems];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.from on NodeList | |
Spread on NodeList |
Test name | Executions per second |
---|---|
Array.from on NodeList | 3296.3 Ops/sec |
Spread on NodeList | 3165.8 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark is comparing two approaches to iterate over a NodeList in JavaScript:
Array.from(listItems)
[...listItems]
(Spread operator)What's Being Tested
The benchmark measures the execution speed of these two approaches on a NodeList. The test case appends 1000 list items to an unordered list (ul
) and then iterates over the list using each approach.
Options Compared
Two options are being compared:
Array.from(listItems)
map()
, filter()
.[...listItems]
(Spread operator)map()
and filter()
.Library and Purpose
The library used is Array.prototype.from()
(for the first option) and Spread operator (...
syntax) (for the second option). Both are part of the ECMAScript 2015 standard.
Special JS Feature or Syntax
There's no special feature or syntax being tested in this benchmark. It's a straightforward comparison of two approaches to iterate over a NodeList.
Other Alternatives
If you're looking for alternative ways to iterate over a NodeList, here are some other options:
for...of
loop: Similar to the spread operator approach, but more concise.forEach()
method: A synchronous method that can be used with NodeLists.Here's an example of how you could rewrite the benchmark using a for...of
loop:
var listItems = document.querySelectorAll('li');
for (const item of listItems) {
// ...
}
And here's an example of how you could use the forEach()
method:
listItems.forEach((item) => {
// ...
});
Keep in mind that these alternatives may not be as efficient as the original two options being compared.