var numbers = [Array(1000).keys()]
var arr = [numbers, numbers, numbers, numbers, numbers]
var results = arr.reduce((acc, cur) => acc.concat(cur), []);
var results = arr.reduce((acc, cur) => [acc, cur], []);
var results = arr.reduce((acc, cur) => {
acc.push(cur);
return acc;
}, []);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
concat | |
spread operator | |
push with spread operator |
Test name | Executions per second |
---|---|
concat | 154852.3 Ops/sec |
spread operator | 38546.2 Ops/sec |
push with spread operator | 9046918.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, the pros and cons of each approach, and other considerations.
Benchmark Description
The benchmark compares three ways to concatenate arrays in JavaScript:
Array.prototype.concat()
...
)push()
method with the spread operator (...
)The test case uses an array of 1000 numbers as input data.
Options Compared
...
): This is a new feature introduced in ECMAScript 2015, which allows for more concise and expressive array operations. It works by spreading the contents of an array into a new array....
): This approach uses the push()
method to add elements to an array while also using the spread operator to provide initial values.Pros and Cons
...
):...
):concat()
and the spread operator, potentially leading to better performance.Library Used
None. This benchmark only uses built-in JavaScript features.
Special JS Feature or Syntax
The spread operator (...
) is a new feature introduced in ECMAScript 2015. It's used extensively in modern JavaScript code and has become a standard part of the language.
Other Considerations
Alternatives
Other alternatives for array concatenation in JavaScript include:
Array.prototype.reduce()
with the initial value set to an empty array.concat
function.However, these alternatives may not be as efficient or expressive as the spread operator (...
) when used correctly.