var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
arr.filter(x => x % 3).map(x => x/100)
arr.flatMap(x => x % 3 ? x/100 : [])
arr.map(x => x % 3 && x/100).filter(Boolean)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter().map() | |
flatMap() | |
mapFilter(Boolean) |
Test name | Executions per second |
---|---|
filter().map() | 94.1 Ops/sec |
flatMap() | 36.8 Ops/sec |
mapFilter(Boolean) | 61.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition: The provided JSON represents a benchmark test comparing three approaches to process an array in JavaScript:
filter()
followed by map()
flatMap()
map()
followed by filter(Boolean)
This is often referred to as the "flatMap vs filter map" or "flatMap vs filter".map" comparison.
Options Compared:
flatMap()
vs filter().map()
: Both methods are used to transform arrays, but flatMap()
returns a new array with all sub-arrays concatenated, while filter()
and .map()
return an array of filtered elements.mapFilter(Boolean)
: This is a variation of the previous approach where the filtering step is combined with the mapping step using the Boolean
function. The idea is to filter out falsy values from the array before mapping.Pros and Cons:
flatMap(): Pros:
filter()
and .map()
because it avoids creating intermediate arrays.Cons:
filter().map(): Pros:
flatMap()
.Cons:
mapFilter(Boolean): Pros:
filter()
step, which can simplify the code.Cons:
filter()
and .map()
steps.Library Usage: None of the provided benchmarks use external libraries. The JavaScript standard library is used throughout.
Special JS Features or Syntax:
flatMap()
is a modern JavaScript feature introduced in ECMAScript 2019 (ES11). It's designed to simplify the process of transforming arrays and combining multiple operations into one step.
Other Alternatives:
Array.prototype.reduce()
instead of map()
or flatMap()
.