var arrayX = [];
for(i=0; i< 1000; i++){
arrayX.push(Math.random());
arrayX.push(Math.random() + 'x');
arrayX.push(Math.random() > 0.5);
}
const copy = arrayX.slice();
const copy = [ arrayX ];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.slice | |
spread operator |
Test name | Executions per second |
---|---|
Array.prototype.slice | 34623.1 Ops/sec |
spread operator | 22666.0 Ops/sec |
Let's dive into the explanation of the benchmark.
What is tested?
The benchmark compares two approaches for creating a shallow copy of an array: the traditional Array.prototype.slice()
method and the new ES6 spread operator ([ ...arrayX ]
).
Options compared:
[ ...arrayX ]
): This method creates a new array by spreading elements of the original array into a new array.Pros and cons of each approach:
[ ...arrayX ]
):slice()
.slice()
because it involves creating intermediate arrays.Library usage:
There is no library used in this benchmark. It's just pure JavaScript code.
Special JS features or syntax:
The spread operator ([ ...arrayX ]
) is a newer feature introduced in ES6 (EcmaScript 2015). It was added to the JavaScript language to provide a concise way to create arrays from iterables.
Other alternatives:
If you need to create a deep copy of an array and want a more efficient alternative to the spread operator, you could consider using Array.prototype.map()
in combination with JSON.parse(JSON.stringify(arrayX))
. This approach is less elegant but can be faster:
const copy = JSON.parse(JSON.stringify(arrayX));
This method works by serializing the original array to a string, parsing that string back into an array (which creates a deep copy of the original array), and then deserializing it from a string again.
Keep in mind that this approach can be slower than using slice()
or the spread operator because it involves creating intermediate objects and strings. However, if you need to create a deep copy of an array for performance-critical code, this method might be worth considering.