var randomNumbers = [];
for (let i = 0; i < 2000; i++) {
randomNumbers.push(Math.random());
}
const copy = [randomNumbers];
const copy = randomNumbers.slice();
const copy = randomNumbers.slice(0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread Operation | |
Array.prototype.slice() | |
Array.prototype.slice(0) |
Test name | Executions per second |
---|---|
Spread Operation | 1873710.0 Ops/sec |
Array.prototype.slice() | 1825417.0 Ops/sec |
Array.prototype.slice(0) | 1704650.2 Ops/sec |
What is tested on the provided JSON?
The benchmark measures the performance of three different approaches to create a copy of an array in JavaScript:
const copy = [...randomNumbers];
): This approach creates a new array by spreading the elements of randomNumbers
. with no arguments (
const copy = randomNumbers.slice();)**: This approach returns a shallow copy of
randomNumbers`, creating a new array. with an argument (0) (
const copy = randomNumbers.slice(0);)**: This approach creates a new array containing only the first element of each sub-array in
randomNumbers`.Options compared
The benchmark compares the performance of these three approaches:
Pros and Cons of each approach:
const copy = [...randomNumbers];
): without arguments (
const copy = randomNumbers.slice();`): with an argument (0) (
const copy = randomNumbers.slice(0);`):randomNumbers
, can be more efficient than other approaches for large arrays.Library and its purpose
There is no external library used in this benchmark. However, JavaScript arrays are based on the ECMAScript specification, which defines the behavior of arrays and their methods, including slice()
.
Special JS feature or syntax
There is no special JS feature or syntax mentioned in this benchmark.
Other alternatives
If you're looking for alternative approaches to create a copy of an array in JavaScript, some other options include:
Array.prototype.concat()
method: const copy = randomNumbers.concat();
JSON.parse(JSON.stringify(randomNumbers))
trick: const copy = JSON.parse(JSON.stringify(randomNumbers));
cloneDeep
functionNote that each of these alternatives has its own trade-offs and performance characteristics, which may be worth considering depending on your specific use case.