var arr = Array(100).fill([{n: ''}]);
var params = [ "hello", true, 7 ];
var other = arr.concat(params);
var params = [ "hello", true, 7 ];
var other = [ arr, params ];
arr.push("hello", true, 7);
var other = arr;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
array.push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 2076648.6 Ops/sec |
spread operator | 2358425.5 Ops/sec |
array.push | 3955302.5 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark compares three ways to concatenate an array in JavaScript: Array.prototype.concat
, the spread operator (...
), and modifying the original array using push
. The test aims to determine which method is the most efficient, considering factors like performance, memory usage, and code readability.
Options Compared
Array.prototype.concat
: This method creates a new array by copying elements from the original array and adding additional elements....
): This method uses the spread operator to create a new array by copying elements from the original array and spreading them into a new array.push
: This method modifies the original array in place, appending elements to it.Pros and Cons
Array.prototype.concat
:...
):concat
, creates a new array with minimal overhead.push
:Library and Special JS Features
In this benchmark, there are no libraries used. However, the ...
spread operator is a feature introduced in ES6, which allows for more concise and expressive code.
Test Cases and Considerations
The test cases cover three scenarios:
Array.prototype.concat
: Tests the performance of concatenating an array using the traditional method....
): Tests the performance of concatenating an array using the spread operator.push
: Tests the performance of modifying the original array in place.When choosing between these methods, consider the trade-offs:
Array.prototype.concat
is a safe choice....
) if your target browser supports it.push
may be the most efficient option.Alternatives
Other alternatives to concatenate arrays in JavaScript include:
Array.from()
and then pushing elements onto it.reduce()
or map()
.