const array1 = [1, 2, 3, 4, 5]
const array2 = [6, 7, 8, 9, 10]
const finalArray = [
array1,
array2
]
const array1 = [1, 2, 3, 4, 5]
const array2 = [6, 7, 8, 9, 10]
const finalArray = array1.concat(array2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using spread operator | |
Using Array.concat |
Test name | Executions per second |
---|---|
Using spread operator | 324855072.0 Ops/sec |
Using Array.concat | 13762200.0 Ops/sec |
Let's break down the provided benchmark.
What is being tested?
The benchmark tests two approaches to merging two arrays in JavaScript:
...
).Array.concat()
.In each test case, we have an initial array array1
and another array array2
. The final result should be a new array containing all elements from both original arrays. We're comparing the performance of these two methods in creating this new array.
Options compared
The two options being compared are:
...
): This is a modern JavaScript feature that allows you to expand an array into multiple arguments, similar to apply()
or concat()
. When used with the syntax [...array1, ...array2]
, it creates a new array containing all elements from both input arrays.Array.concat()
: This method takes two or more arrays as arguments and returns a new array containing all elements from those arrays. In this case, we're passing array1
and array2
to the concat()
method.Pros and Cons
Using spread operator (...
)
Pros:
Cons:
Using Array.concat()
Pros:
Cons:
Library usage
There is no explicit library mentioned in the benchmark definition, but we can assume that the Array
object and its methods (e.g., concat()
) are part of the built-in JavaScript API.
Special JS feature
There is no special JavaScript feature or syntax used in this benchmark. It only relies on standard JavaScript language features and APIs.
Other alternatives
If you wanted to create a new array by merging two arrays, other alternatives could include:
Array.prototype.reduce()
(although this might be less efficient due to the overhead of function calls)push()
and indexingHowever, for simple cases like this one, the spread operator or concat()
method are usually the most straightforward and performant choices.