var children = document.body.children
var other = Array.prototype.slice.call(children);
var other = [ children ]
var other = [];
[].push.apply(other, children)
var other = Array.from(children);
var other = Object.values(children);
--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 | 181679.4 Ops/sec |
spread operator | 167057.8 Ops/sec |
push apply into empty array | 694577.9 Ops/sec |
Array.from | 139281.2 Ops/sec |
Object.values | 36432.2 Ops/sec |
Let's dive into the benchmark test case provided.
What is being tested?
This test case compares the performance of five different methods for creating a new array by copying the elements from another array (children
). The methods being compared are:
Array.prototype.slice.call(children)
[ ...children ]
(spread operator)[]; Array.prototype.push.apply(other, children)
(push apply into empty array)Array.from(children)
Object.values(children)
What options are compared?
The test case compares the execution time of these five methods for creating a new array by copying the elements from another array (children
). The execution time is measured in executions per second.
Pros and Cons:
Array.prototype.slice.call(children)
call()
method on slice()
function[ ...children ]
(spread operator)[]; Array.prototype.push.apply(other, children)
Array.from(children)
Object.values(children)
Other considerations:
children
variable, which is assumed to be an HTMLCollection or NodeList obtained from document.body.children
.Library and special JS feature:
[ ...children ]
) is a special JavaScript feature introduced in ES6 (2015).Alternatives:
Array.prototype.concat()
and using a loop to push each element into the new array. However, these methods are not compared in this specific test case.I hope this explanation helps!