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] : [])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter().map() | |
flatMap() |
Test name | Executions per second |
---|---|
filter().map() | 957.2 Ops/sec |
flatMap() | 474.8 Ops/sec |
Let's break down the benchmark and its results.
What is being tested?
The provided JSON represents a JavaScript microbenchmark that compares two approaches for processing an array: filter().map()
and flatMap()
. The test case creates an array with 100,000 elements using a while loop and then applies each approach to it. The resulting array is filtered (removing every third element) and then mapped (dividing the remaining elements by 100).
Options being compared
There are two options being compared:
filter().map()
flatMap()
Pros and Cons of each approach:
filter().map()
flatMap()
, especially for large arrays, since it creates an intermediate array and then maps over it.flatMap()
Library and purpose
There is no library mentioned in the provided JSON. However, flatMap()
is a built-in JavaScript method introduced in ECMAScript 2019.
Special JS feature or syntax
The test case does not use any special JavaScript features or syntax beyond the flatMap()
method.
Other alternatives
If you wanted to compare additional approaches, you could consider adding more options, such as:
forEach
instead of map
Array.prototype.reduce()
)Keep in mind that each alternative would require additional configuration and benchmarking code.
Benchmark preparation code
The provided JSON includes the following script preparation code:
var arr = [];
var i = 0;
while (i <= 1E5) {
arr[i] = i++;
}
This code creates an array with 100,000 elements using a while loop.