const ITERATIONS = 500000;
var index = ITERATIONS / 2;
var n = Math.random();
var list = [];
for (let i = 0; i < length; i += 1) {
list.push(Math.random());
}
const clone = [list];
const clone = list.slice();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array clone with spread operator | |
Array clone with slice |
Test name | Executions per second |
---|---|
Array clone with spread operator | 16491702.0 Ops/sec |
Array clone with slice | 13509463.0 Ops/sec |
What is tested?
The provided JSON benchmark tests the performance of two approaches to create a copy of an array: the spread operator (...
) and the slice()
method.
Options compared
The benchmark compares the performance of these two methods:
...
): This method creates a new array by copying elements from the original array.slice()
): This method returns a shallow copy of a portion of an array, starting at the specified start index and ending at the specified end index.Pros and Cons
.slice()
alternative):slice()
):Library usage
In this benchmark, no specific library is used.
Special JavaScript features or syntax
This benchmark uses the following special feature:
...
) uses destructuring assignment to create a new array.Alternatives
Other alternatives for creating copies of arrays or objects include:
Array.prototype.slice.call()
with an array constructor (e.g., new Array(length)
).Object.assign()
, which creates a shallow copy of an object.lodash
library's cloneDeep()
function, which can create deep copies of complex data structures.Keep in mind that these alternatives may have different performance characteristics or requirements depending on the specific use case.