var params = Array.from({length: 10000}, () => 1)
var other = params.slice();
var params = Array.from({length: 10000}, () => 1)
var other = [ params ]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.slice large | |
spread operator large |
Test name | Executions per second |
---|---|
Array.prototype.slice large | 4780.3 Ops/sec |
spread operator large | 4718.1 Ops/sec |
The benchmark titled "Array.prototype.slice vs spread operator large arrays" aims to compare the performance of two methods for copying large arrays in JavaScript: the traditional Array.prototype.slice()
method and the modern ES6 spread operator ([...]
).
Test Case: Array.prototype.slice large
var params = Array.from({length: 10000}, () => 1);
var other = params.slice();
params
) filled with 10,000 elements, all set to 1. It then uses the slice()
method to create a shallow copy of that array (other
). The slice()
method is well-established in JavaScript and allows for copying parts of an array. When called without arguments, it copies the entire array.Test Case: spread operator large
var params = Array.from({length: 10000}, () => 1);
var other = [ ...params ];
[...]
) to create a new array. The spread operator is a concise syntax introduced in ES6 that allows for the expansion of elements from an iterable (in this case, the array params
) into a new array.The results indicate the Executions Per Second for each test. Here are the numbers from the benchmark:
Pros:
Cons:
Pros:
Cons:
slice()
.Other alternatives for copying arrays in JavaScript include:
Array.from(): This method can also be used to create a new array instance from an existing array-like or iterable object.
var other = Array.from(params);
Concat Method: Using the concat()
method to copy an array by combining it with an empty array:
var other = [].concat(params);
Each of these methods (like Array.from
and concat
) has its pros and cons regarding performance and readability as well. Ultimately, the choice depends on the specific scenario, codebase requirements, and developer preferences.