var arr = Array(10_000).fill(1)
arr.reduce((acc, x, index) => acc.concat(x, index % 2 ? x : []), [])
arr.flatMap((x, index) => [x, index % 2 && x]).filter(Boolean)
arr.reduce((acc, x, index) => { acc.push(x); if(index % 2) { acc.push(x) } return acc; }, [])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Reduce concat | |
FlatMap | |
Reduce push |
Test name | Executions per second |
---|---|
Reduce concat | 8.6 Ops/sec |
FlatMap | 3188.7 Ops/sec |
Reduce push | 35196.3 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark measures the performance of three different approaches to concatenate arrays: reduce
with concatenation, flatMap
, and reduce
with push
.
The Script Preparation Code
defines an array arr
with 10,000 elements, all filled with the value 1
. This array is used as input for each benchmark.
Test Cases
There are three test cases:
reduce
method to concatenate two arrays. The callback function takes three arguments: acc
, x
, and index
. It concatenates x
with acc
using the comma operator (acc.concat(x, index % 2 ? x : [])
). The result is then returned.flatMap
method to create a new array with transformed elements. The callback function takes two arguments: x
and index
. It returns an array containing x
and either x
or an empty array, depending on whether index
is even.reduce
method to push elements onto an accumulator array. The callback function takes three arguments: acc
, x
, and index
. It pushes x
onto acc
using the push
method. If index
is even, it also pushes x
again onto acc
.Library Used
The flatMap
method uses the Array.prototype.flatMap() method, which was introduced in ECMAScript 2019.
Special JS Feature/Syntax
None of the test cases use any special JavaScript features or syntax that are not widely supported. However, it's worth noting that the flatMap
method is a relatively new addition to the language, and its behavior might be affected by certain optimizations or compiler settings.
Pros and Cons of Different Approaches
Here are some pros and cons of each approach:
reduce
with concatenation.flatMap
, but might be slightly faster due to the use of push
.flatMap
.Other Alternatives
If you're interested in exploring alternative approaches, here are a few options:
flatMap
, but it returns a flattened array instead of an array of arrays.+
Array.prototype.concat(): You can use the
mapmethod to transform elements and then concatenate them using the
concat` method.Keep in mind that the performance differences between these alternatives might be significant, depending on the size and structure of your data.