var baseArray = []
for (var i = 0; i < 5000; i++) {
baseArray.push((Math.floor(Math.random() * Math.floor(1000000))).toString(16))
}
var other = baseArray.slice();
var other = [ baseArray ]
var other = baseArray.slice(0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.slice() | |
spread operator | |
Array.prototype.slice(0) |
Test name | Executions per second |
---|---|
Array.prototype.slice() | 2095941.6 Ops/sec |
spread operator | 2325990.8 Ops/sec |
Array.prototype.slice(0) | 2365071.8 Ops/sec |
Let's dive into the benchmark.
What is tested?
The provided JSON represents a JavaScript microbenchmark that compares three approaches for creating a copy of an array: Array.prototype.slice()
, spread operator
(new ES6 syntax), and slice(0)
(an optimized version of slice()
).
Options compared:
Array.prototype.slice()
: This method creates a shallow copy of the original array by returning a new array object with references to the same elements as the original array.spread operator
([ ...baseArray ]
): This syntax creates a new array by spreading the elements of baseArray
into a new array.slice(0)
: This method creates an empty array and then pushes all elements from the original array onto it.Pros and Cons of each approach:
Array.prototype.slice()
:spread operator
([ ...baseArray ]
):slice(0)
:slice()
that creates an empty array and pushes elements onto it, reducing memory allocation.Library usage
None in this benchmark.
Special JS feature or syntax
The benchmark uses the new ES6 spread operator ([ ...baseArray ]
), which was introduced in ECMAScript 2015.
Other considerations
This benchmark is likely designed to test performance, so it's essential to consider factors like:
Alternatives
Other approaches for creating an array copy could include:
Array.prototype.concat()
: Creates a new array by concatenating the elements of the original array.Array.prototype.slice().concat()
: Similar to slice()
followed by concat()
, which can be slower due to the extra function call.Object.assign()
: Not suitable for creating an array copy, as it modifies the source object.Keep in mind that this benchmark is designed to compare specific approaches, and different performance characteristics may emerge when using alternative methods.