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 | 115241224.0 Ops/sec |
spread operator | 66307936.0 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and their pros and cons.
What is being tested?
The benchmark compares two approaches to create a copy of an array in JavaScript:
Array.prototype.slice()
[...params]
Options compared:
Array.prototype.slice()
: This method returns a shallow copy of the original array, creating a new array object with references to the same elements as the original array.[...params]
: This syntax creates a new array by iterating over each element in params
and adding it to a new array.Pros and Cons:
Array.prototype.slice()
:[...params]
:params
. It also avoids creating an intermediate array.Library and its purpose:
There is no library used in this benchmark. The focus is solely on comparing the two JavaScript methods.
Special JS feature or syntax:
The benchmark uses the new ES6 spread operator, which was introduced in ECMAScript 2015 (ES6). It's a shorthand way to create a new array by iterating over each element in an existing array or other iterable.
Other alternatives:
If you want to avoid the spread operator and still create a copy of an array, you can use the Array.prototype.concat()
method:
var params = [ "hello", true, 7 ];
var other = Array.prototype.concat.call([], params);
Alternatively, you can use the Array.from()
method:
var params = [ "hello", true, 7 ];
var other = Array.from([ params ], (item) => item);
However, these approaches are generally less efficient and more verbose than using the spread operator.
The benchmark results show that Chrome 93 is faster with both Array.prototype.slice()
and the new ES6 spread operator. This suggests that the performance difference between these two methods is relatively small, but still worth considering when writing JavaScript code.