var params = [ 1, 2, 3, 5, 8, 13, 21, 34 ];
var other = params.slice();
var params = [ 1, 2, 3, 5, 8, 13, 21, 34 ];
var other = [params];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.slice() | |
spreading operator [...array] |
Test name | Executions per second |
---|---|
Array.slice() | 13003736.0 Ops/sec |
spreading operator [...array] | 6952852.0 Ops/sec |
Let's break down the provided benchmark.
What is tested?
The benchmark compares two approaches to create an array: using the Array.slice()
method and the spreading operator (...array
).
Options compared:
Array.slice()
: This method returns a shallow copy of a portion of an array. It creates a new array object with the specified elements, without modifying the original array....array
): This syntax creates a new array by iterating over the elements of the original array and adding them to a new array.Pros and Cons:
Array.slice()
:...array
):Array.slice()
for large arrays due to the overhead of creating a new array object.Library and syntax:
The benchmark uses JavaScript's built-in Array
class, which is part of the ECMAScript standard. The spreading operator (...array
) was introduced in ECMAScript 2015 (ES6) as a way to create new arrays from existing ones.
Special JS feature or syntax:
None mentioned in this specific benchmark.
Other alternatives:
For creating an array, you can also use:
Array.from()
: Creates a new array from an iterable object (e.g., an array, string, or set).concat()
: Concatenates one or more arrays into a single array.push()
, unshift()
, and other methods for modifying the end of an array.However, in this specific benchmark, the only alternatives being compared are Array.slice()
and the spreading operator (...array
).