var arr = Array(10_000).fill(undefined).map((_, idx) => idx)
const newArr = arr.slice(0);
const newArr = arr.concat([]);
const newArr = [arr];
const newArr = Array.from(arr);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.slice() | |
Array.prototype.concat() | |
Spread syntax | |
Array.from() |
Test name | Executions per second |
---|---|
Array.prototype.slice() | 350973.5 Ops/sec |
Array.prototype.concat() | 182203.2 Ops/sec |
Spread syntax | 342559.0 Ops/sec |
Array.from() | 309849.1 Ops/sec |
Overview
The provided benchmark measures the performance of four different approaches for creating a shallow copy of an array in JavaScript: Array.prototype.slice()
, Array.prototype.concat()
, the spread syntax (...
), and Array.from()
.
Options Compared
Array.prototype.slice()
: This method returns a new array containing all elements from the original array, starting at the specified index.Array.prototype.concat()
: This method returns a new array containing all elements from the original array and possibly additional elements passed as arguments....
): This syntax creates a new array by spreading the elements of the original array into the new array.Array.from()
: This static method creates a new array from an array-like or iterable object.Pros and Cons
Array.prototype.slice()
:Array.prototype.concat()
:slice()
for shallow copies, as it creates a new array with all elements from the original array and possibly additional ones....
):Array.from()
:slice()
for shallow copies, as it creates a new array from an iterable object.Library and Purpose
None of the methods use external libraries in this benchmark.
Special JS Features or Syntax
The benchmark uses the spread syntax (...
), which is a relatively recent addition to JavaScript. It allows creating new arrays by spreading elements from an existing array into the new array.
Other Alternatives
Besides the four methods mentioned, other approaches for creating shallow copies of arrays in JavaScript include:
JSON.parse(JSON.stringify(arr))
, but this method can be slower and less efficient than the others.However, these alternatives are not included in this benchmark.