var arr = Array(10_000).fill(0)
arr.reduce((acc, x) => [acc, x, x], [])
arr.flatMap(x => [x, x])
arr.reduce((acc, x) => { acc.push(x, x); return acc }, [])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce with concat | |
flatMap | |
reduce with push |
Test name | Executions per second |
---|---|
reduce with concat | 14.3 Ops/sec |
flatMap | 740.2 Ops/sec |
reduce with push | 22024.4 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Definition JSON
The benchmark defines three test cases:
flatMap
: Tests the performance of the flatMap()
method, which creates a new array with the results of applying a provided function to each element in the original array.reduce.concat
: Tests the performance of the concat()
method used inside the reduce()
method, which combines multiple arrays into one.reduce.push
: Tests the performance of the push()
method used inside the reduce()
method, which adds an element to the end of an array.Options Compared
The benchmark compares the performance of three approaches:
flatMap()
: Uses the flatMap()
method to transform the array.concat()
+ reduce()
: Uses the concat()
method to combine arrays, and then uses the reduce()
method to accumulate the results.push()
+ reduce()
: Uses the push()
method to add elements to the accumulator array inside the reduce()
method.Pros and Cons of Each Approach
concat()
. However, it may not be suitable for large datasets due to its memory usage.flatMap()
due to the overhead of concatenating arrays and creating temporary arrays. However, it's more memory-efficient and can handle larger datasets.concat() + reduce()
because it avoids creating intermediate arrays using concat()
. However, it may lead to slower performance due to the repeated push operations inside the reduce()
method.Library Used
There is no specific library used in this benchmark. The methods being tested are part of the JavaScript standard library.
Special JS Features or Syntax
The benchmark uses modern JavaScript features such as:
=>
)10_000
for a large number)flatMap()
, which is a newer method introduced in ECMAScript 2019Other Considerations
When choosing an approach, consider the following factors:
concat()
+ reduce()
or push()
+ reduce()
.flatMap()
might be a better choice due to its potential for faster execution.Alternatives
If you're interested in exploring alternative approaches, consider the following:
reduce()
with an array comprehension (e.g., [...arr, ...arr]
) instead of concat()
. This can be slower but provides a concise syntax.map
and reduce
methods, to see if they offer better performance.