var arr = Array(10_000).fill(0)
arr.reduce((acc, x) => {acc.push(x, x); return acc}, [])
arr.flatMap(x => [x, x])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce with concat | |
flatMap |
Test name | Executions per second |
---|---|
reduce with concat | 5664.4 Ops/sec |
flatMap | 4488.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance difference between two approaches to process an array of numbers:
reduce
with concatenation (arr.reduce((acc, x) => {acc.push(x, x); return acc}, [])
)flatMap
Options Compared
In this benchmark, we're comparing the performance of two different methods to achieve a similar result:
reduce
: A method that applies a reduction function (in this case, concatenating each element with itself) to an array, accumulating the results in an accumulator.flatMap
: A method that flattens an array of arrays into a single array.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
flatMap
: Pros:reduce
with concatenationLibrary/Functionality Used
In this benchmark, we're using the following libraries/functions:
Array.prototype.reduce()
: A built-in JavaScript method that applies a reduction function to an array.Array.prototype.flatMap()
: A built-in JavaScript method (introduced in ECMAScript 2019) that flattens an array of arrays into a single array.Special JS Feature/Syntax
In this benchmark, we're using the flatMap
method, which is a relatively new feature introduced in ECMAScript 2019. This allows for concise and expressive array processing without requiring explicit looping or memory allocations.
Other Alternatives
If you don't have access to modern browsers that support flatMap
, you can still achieve similar results using other methods, such as:
map
followed by concat
flatten
However, these alternatives may not be as concise or efficient as the original flatMap
approach.