const arr1 = [];
const arr2 = [];
const arr3 = [];
const arrs = []
for (let i = 0; i < 2000; i++) {
arr1.push(i);
}
for (let i = 0; i < 3000; i++) {
arr2.push(i);
}
for (let i = 0; i < 1000; i++) {
arr3.push(i);
}
arrs.push(arr1, arr2, arr3);
arrs.reduce((memo, val) => {
return memo.concat(val);
}, []);
const arr1 = [];
const arr2 = [];
const arr3 = [];
const arrs = []
for (let i = 0; i < 2000; i++) {
arr1.push(i);
}
for (let i = 0; i < 3000; i++) {
arr2.push(i);
}
for (let i = 0; i < 1000; i++) {
arr3.push(i);
}
arrs.push(arr1, arr2, arr3);
arrs.reduce((memo, val) => {
return [memo, val];
}, []);
const arr1 = [];
const arr2 = [];
const arr3 = [];
const arrs = []
for (let i = 0; i < 2000; i++) {
arr1.push(i);
}
for (let i = 0; i < 3000; i++) {
arr2.push(i);
}
for (let i = 0; i < 1000; i++) {
arr3.push(i);
}
arrs.push(arr1, arr2, arr3);
arrs.reduce((memo, val) => {
memo.push(val);
return memo;
}, []);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 18784.6 Ops/sec |
spread operator | 12473.0 Ops/sec |
Push | 17653.5 Ops/sec |
Overview
The provided benchmark measures the performance of three different approaches for concatenating arrays in JavaScript: Array.prototype.concat
, the spread operator, and the push
method.
Options compared
Array.prototype.concat"
: This method creates a new array by copying all elements from one or more source arrays....
): This operator is used to create a new array by spreading elements from an existing array or other iterable.push
method: This method adds one or more elements to the end of an array.Pros and Cons
Array.prototype.concat
:...
):push
method:concat
for large arrays, and may cause issues with array length calculations.Library and purpose
None of the test cases use any external libraries. However, it's worth noting that modern JavaScript engines often include optimizations for array operations, which may affect performance.
Special JS features or syntax
The spread operator (...
) is a relatively new feature introduced in ECMAScript 2015 (ES6). While most modern browsers support it, older versions of Chrome and other browsers may not. The push
method has been part of the JavaScript language since its inception, but it's worth noting that some older browsers may have issues with array length calculations.
Alternatives
Other methods for concatenating arrays in JavaScript include:
Array.prototype.join()
: This method creates a new string by joining all elements from an array.Array.prototype.concat()
(with a callback function): This method creates a new array by applying a callback function to each element of the source arrays.However, these alternatives may not be as efficient or flexible as the three options tested in this benchmark.