var arr = Array(10_000).fill({arr: [0,1]})
arr.reduce((acc, x) => {acc.push(x.arr); return acc}, [])
arr.flatMap(x => x.arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce with concat | |
flatMap |
Test name | Executions per second |
---|---|
reduce with concat | 10836.5 Ops/sec |
flatMap | 4128.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition and Preparation Code
The benchmark is comparing two approaches: reduce
with push
and flatMap
. The preparation code creates an array arr
with 10,000 elements, each containing a nested array [0,1]
.
Options Compared
The two options being compared are:
reduce((acc, x) => {acc.push(x.arr); return acc}, [])
: This approach uses the reduce()
method to iterate over the array and push the values of the inner arrays into a new accumulator array.arr.flatMap(x => x.arr)
: This approach uses the flatMap()
method to create a new array with the flattened elements of the inner arrays.Pros and Cons
reduce
with push
:flatMap
:Library and Purpose
The flatMap()
method uses the ECMAScript 2019 (ES2019) standard's Array.prototype.flatMap()
method. This method returns a new array with the result of calling a provided callback function on every element in this array, passing the current element and an optional collection size as arguments.
Special JS Feature or Syntax
There is no special feature or syntax mentioned in the benchmark definition that requires specific knowledge to understand.
Other Alternatives
If you were to implement these approaches from scratch without using built-in methods like reduce()
or flatMap()
, you could use:
for
loops, while
loops) to iterate over the array and build the result.Set
, Map
, or even a custom object.Keep in mind that these alternatives would likely be less efficient than using built-in methods like reduce()
or flatMap()
.