var arr = new Array(100000).fill(1);
arr.flatMap(() => [1, 2]);
arr.map(() => [1, 2]).flat();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Test flatMap | |
Test map/flat |
Test name | Executions per second |
---|---|
Test flatMap | 529.3 Ops/sec |
Test map/flat | 110.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The provided benchmark measures the performance difference between flatMap
and two approaches that emulate its behavior: map/flat
. The goal is to understand which approach yields the best performance for array flattening operations.
Tested Options
There are three test cases:
arr.flatMap(() => [1, 2])
: This is the original flatMap
method being tested.arr.map(() => [1, 2]).flat()
: This is an implementation of map/flat
, where the map
function generates an array of arrays and then calls flat
to flatten it.Array.prototype.flatMap.call(arr, () => [1, 2])
: This approach uses Array.prototype.flatMap
(a static method) to call the callback function on each element in the array.Pros and Cons
arr.flatMap(() => [1, 2])
:arr.map(() => [1, 2]).flat()
: map
and flat
methods.Array.prototype.flatMap.call(arr, () => [1, 2])
:Library and Special JS Feature
There is no specific library used in this benchmark. However, it's essential to note that flatMap
is a relatively new feature introduced in ECMAScript 2020 (ES10). If you're targeting older browsers or environments, these tests may not be directly applicable.
Other Alternatives
If you need to implement array flattening without using map/flat
, other approaches might include:
forEach
: Iterate over each element and manually push values into a new array.flatMap
method: Define a custom function that uses existing JavaScript features like map
, reduce
, or forEach
.flatten
functions, which can be used as alternatives to flatMap
.