var arr = [];
var i = 0;
while (i <= 1E5) arr[i] = i++;
arr.filter(x => x % 12 && x % 5 && x % 3).map(x => x/100)
arr.flatMap(x => x % 12 && x % 5 && x % 3 ? x/100 : [])
arr.reduce((newArray, x) => {
if (x % 12 && x % 5 && x % 3) {
newArray.push(x / 100)
}
return newArray
}, [])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter().map() | |
flatMap() | |
reduce() |
Test name | Executions per second |
---|---|
filter().map() | 411.7 Ops/sec |
flatMap() | 354.2 Ops/sec |
reduce() | 622.6 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript benchmark, specifically measuring the performance differences between three methods: flatMap()
, filter().map()
, and reduce()
. These methods are used to process arrays in JavaScript.
What is tested?
flatMap()
: This method flattens an array by applying a mapping function to each element and recursively iterating over the resulting arrays. In this benchmark, it's used with a conditional statement to filter out certain numbers from the array before transforming them.filter().map()
: This approach combines filtering (removing elements that don't meet a condition) with mapping (transforming remaining elements). It filters out numbers that are divisible by 12 and 5, then maps each remaining number to itself divided by 100.reduce()
: In this benchmark, it's used as a way to accumulate the results of filtering and transforming the array, rather than returning an entirely new array.Options compared
flatMap()
vs filter().map()
filter().map()
vs reduce()
Pros and Cons
flatMap()
Pros:
Cons:
flatMap()
returns an empty array or a single elementfilter().map()
Pros:
Cons:
flatMap()
directly, especially for large datasetsreduce()
Pros:
Cons:
Library usage
There are no libraries explicitly mentioned in the provided code snippets, but the flatMap()
function is a part of JavaScript's built-in Array prototype.
However, some external libraries might be used for additional functionality or performance optimizations. For example:
Special JS features or syntax
The provided benchmark code snippets use the following modern JavaScript features:
x => x % 12 && x % 5 && x % 3
)x/100
)Alternatives
For those interested in exploring alternative approaches or optimizing their own array processing:
Keep in mind that each alternative has its own trade-offs, complexity levels, and applicability depending on the specific use case and constraints.