var params = [];
for (var i = 0; i < 500; i++) {
params.push(i + '_hi there');
params.push(true);
params.push(i);
}
var other = params.slice();
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 | 14324.9 Ops/sec |
spread operator | 815207.4 Ops/sec |
Let's dive into the benchmark.
What is tested?
The provided JSON represents a JavaScript microbenchmark that compares two approaches to create a shallow copy of an array: Array.prototype.slice()
and the new ES6 spread operator (...
). The benchmark tests which approach is faster for long arrays.
Options compared
There are two options being compared:
Array.prototype.slice()
: This method creates a shallow copy of an array by returning a new array object with references to the original elements....
): This operator creates a new array by taking the elements from an existing array.Pros and Cons
Here's a brief overview of each approach:
Array.prototype.slice()
: Pros:...
): Pros:Array.prototype.slice()
Library and syntax
There is no external library being used in this benchmark. The spread operator (...
) is a built-in JavaScript feature introduced in ES6.
Special JS features or syntax
The benchmark uses the ES6 spread operator (...
), which was introduced as a new syntax feature in ES6.
Other alternatives
While not directly related to the Array.prototype.slice()
vs spread operator comparison, other approaches to create shallow copies of arrays include:
Array.from()
: Creates a new array from an iterable or array._copyArray()
or _cloneArray()
functions: Custom functions that manually iterate through the original array and create a new copy.Keep in mind that these alternatives may have different performance characteristics compared to the spread operator.
Benchmark preparation code
The provided Script Preparation Code
initializes an empty array params
with 500 elements, using a loop. This creates a long array for the benchmark.
Individual test cases
Each test case is represented by a separate object in the JSON array:
Array.prototype.slice()
: Creates a new array by calling slice()
on the original array....
): Creates a new array by using the spread operator to take elements from the original array.The benchmark runs both test cases and reports their performance results.