var arr = Array(10_000).fill(0)
arr.reduce((acc, x) => acc.concat(x).concat(x), [])
arr.flatMap(x => [x, x])
arr.reduce((acc, x) => [acc, x, x], [])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce with concat without destructuring | |
flatMap | |
reduce with concat with destructuring |
Test name | Executions per second |
---|---|
reduce with concat without destructuring | 1.4 Ops/sec |
flatMap | 4694.7 Ops/sec |
reduce with concat with destructuring | 18.9 Ops/sec |
Let's break down the provided benchmark JSON and explain what is being tested.
Benchmark Definition
The benchmark defines three test cases, each comparing different approaches to concatenate arrays in JavaScript:
arr.reduce((acc, x) => acc.concat(x).concat(x), [])
: This approach uses the reduce()
method with a callback function that concatenates x
twice and returns the result.arr.flatMap(x => [x, x])
: This approach uses the flatMap()
method to flatten an array of arrays into a single array.arr.reduce((acc, x) => [...acc, x, x], [])
: This approach uses the spread operator (...
) to create a new array and concatenate x
twice.Options Compared
The benchmark compares three options:
concat()
method to concatenate arrays.flatMap()
method to flatten an array of arrays into a single array....
) to create a new array and concatenate x
twice.Pros and Cons
Here are some pros and cons for each approach:
concat()
since it avoids creating intermediate arrays, but still requires JavaScript knowledge.Libraries and Special JS Features
None of the test cases explicitly use any libraries beyond what's built into JavaScript. However, the flatMap()
method is a part of ECMAScript 2019 (ES2020) standard, which may require modern browsers to execute correctly.
Test Case Explanations
reduce()
with concatenation and returns a new array.flatMap()
, which takes an iterable as input and flattens it into a single array.reduce()
again, but this time with the spread operator to create a new array.Alternatives
Other approaches to concatenate arrays in JavaScript include:
Array.prototype.push()
method to add elements to an array.Array.from()
and Set.prototype.add()
for more efficient results.Keep in mind that these alternatives may have different performance characteristics, ease of use, or code readability compared to the approaches tested in this benchmark.