var dom = document.body.querySelectorAll('*')
var other = Array.prototype.slice.call(dom);
var other = [ dom ]
var other = [];
[].push.apply(other, dom)
var other = Array.from(dom);
var other = Object.values(dom)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
spread operator | |
push apply into empty array | |
Array.from | |
Object.values |
Test name | Executions per second |
---|---|
slice | 4501752.0 Ops/sec |
spread operator | 2128118.5 Ops/sec |
push apply into empty array | 5340874.0 Ops/sec |
Array.from | 1990205.5 Ops/sec |
Object.values | 3814065.0 Ops/sec |
This benchmark compares different methods for creating an array from all the elements found in a webpage's body
using HTML DOM APIs.
Options Compared:
slice: Uses Array.prototype.slice.call(dom)
to create a new array by "copying" the elements of the NodeList
.
Spread Operator: Utilizes [...dom]
to expand the elements of the NodeList
directly into a new array. This is an ES6 feature introduced for concise array manipulation.
push.apply(): Creates an empty array (other = [];
) and then uses [].push.apply(other, dom)
to add all elements from the NodeList
into the new array one by one.
Array.from(): Leverages the Array.from(dom)
method, which is designed specifically for converting iterable objects (like NodeList
) into arrays.
Object.values(): This approach uses Object.values(dom)
, which returns an array of the values present in the DOM node object representing the body.
Pros and Cons:
slice: Widely understood, generally performant but might have a slight overhead compared to newer methods.
Spread Operator: Concise, modern syntax, often considered performant.
push.apply(): Less efficient than other options due to its iterative nature of adding elements one by one.
Array.from(): Designed for conversion, generally performant and readable.
Object.values(): Only returns values, not the actual DOM nodes themselves, so it might not be suitable if you need to work with the nodes directly.
Alternatives:
document.body.querySelectorAll('*')
which are efficient and often preferred over iterating through a NodeList
.Let me know if you'd like more details on any specific aspect!