var arr = Array(10_000).fill(0)
arr.flatMap((x) => [[1, 2], [1, 2]].flatMap(y => [x, y]))
arr.map((x) => [[1, 2], [1, 2]].map(y => [x, y])).flat(2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
flatmap | |
map+flat |
Test name | Executions per second |
---|---|
flatmap | 566.3 Ops/sec |
map+flat | 1327.6 Ops/sec |
I'd be happy to help explain the provided benchmark.
Benchmark Overview
The benchmark measures the performance difference between two approaches:
flatMap
with an arrow functionmap
followed by flat(2)
with an arrow functionScript Preparation Code
The script preparation code is:
var arr = Array(10,000).fill(0);
This creates an array of 10,000 zeros.
Html Preparation Code
There is no html preparation code provided.
Library Usage
In the benchmark, we can see that it uses the Array.prototype.flatMap()
and Array.prototype.map()
methods. These methods are part of the ECMAScript standard and do not require any additional libraries to be included.
However, in some browsers, flat(2)
is not supported by default. In this case, it's possible that a polyfill or transpiler was used to make flat
work.
Special JavaScript Features/Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark.
Benchmark Test Cases
The test cases compare the performance of two approaches:
flatMap
: Using flatMap()
with an arrow function to flatten an array of arrays.arr.flatMap((x) => [[1, 2], [1, 2]].flatMap(y => [x, y]));
map + flat(2)
: Using map()
followed by flat(2)
with an arrow function to flatten an array of arrays.arr.map((x) => [[1, 2], [1, 2]].map(y => [x, y])).flat(2);
Benchmark Results
The benchmark results show the performance of each approach on a Chrome browser:
map + flat
: 1327.55 executions per secondflatMap
: 566.32 executions per secondOther Alternatives
If the flatMap
method was not supported by the browser, alternative approaches could have been used, such as:
flatMap
using map()
and concat()
.flat(2)
, such as Lodash or Underscore.js.However, in this case, the Array.prototype.flatMap()
method is used, which is a built-in feature of JavaScript and does not require any additional libraries to be included.