var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
arr.map(x => x/100).filter(x => x % 3)
arr.flatMap(x => x % 3 ? x/100 : [])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter().map() | |
flatMap() |
Test name | Executions per second |
---|---|
filter().map() | 97.7 Ops/sec |
flatMap() | 51.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare the performance of two JavaScript methods: map()
followed by filter()
, and flatMap()
alone. The benchmark uses an array arr
that grows dynamically from 1 to 100,000 elements using a while
loop.
Options Compared
Two approaches are being compared:
map().filter()
: This approach applies the transformation function (in this case, dividing by 100 and checking for divisibility by 3) twice: first using map()
, which returns a new array with transformed elements, and then using filter()
, which returns an array containing only the filtered elements.flatMap()
: This approach applies the transformation function (same as above) directly to the original array, returning a single iterable sequence with transformed elements.Pros and Cons
map().filter()
:
Pros:
Cons:
flatMap()
:
Pros:
Cons:
flatMap()
methodLibrary Usage
The benchmark uses no external libraries.
Special JS Features or Syntax
There are no special JavaScript features or syntax being tested in this benchmark. The focus is solely on comparing the performance of these two approaches.
Other Alternatives
In addition to map()
and flatMap()
, other alternatives for transforming arrays could include:
map
and filter
functionsKeep in mind that the choice of approach depends on the specific requirements and constraints of the project.