var params = [ "hello", true, 7 ];
var other = params.slice();
var params = [ "hello", true, 7 ]
var other = [ params ]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.slice | |
spread operator |
Test name | Executions per second |
---|---|
Array.prototype.slice | 89184912.0 Ops/sec |
spread operator | 66215184.0 Ops/sec |
Let's break down the benchmark and its options.
Benchmark Purpose
The benchmark compares the performance of two approaches for creating a shallow copy of an array: the Array.prototype.slice()
method and the new ES6 spread operator ([ ...params ]
).
Options Compared
[ ...params ]
): This operator creates a new array by taking all elements from the params
array.Pros and Cons of Each Approach
.slice()
).[ ...params ]
):Library/Function Used None, as this benchmark only compares two native JavaScript methods.
Special JS Feature/Syntax
The spread operator ([ ...params ]
) is a new feature introduced in ECMAScript 2015 (ES6). It's designed to simplify array creation and copying by allowing you to take elements from an existing array using the ...
syntax.
Other Alternatives
In addition to these two methods, there are other ways to create a shallow copy of an array, such as:
Array.prototype.slice()
method with no arguments (which creates an empty array)._.cloneDeep()
) or a dedicated array cloning function.However, for simple cases where you only need to create a shallow copy of an array, the spread operator and Array.prototype.slice()
methods are likely sufficient.