var length = 1000000;
var arr = Array.from(Array(length).fill(0),(n, index)=>({date: Math.round(Math.random()*length), internalId: index }) );
const ids = arr.filter((item) => true).map(item => item.internalId);
const ids = arr.flatMap((item) => item.date > 1 ? item.internalId : []);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter + map | |
flatMap |
Test name | Executions per second |
---|---|
filter + map | 34.6 Ops/sec |
flatMap | 11.7 Ops/sec |
Let's dive into explaining the provided JSON benchmark.
Benchmark Overview
The benchmark is designed to compare two approaches: filter
+ map
and flatMap
. Both methods are used to extract the internalId
property from an array of objects, but they differ in their implementation.
Options Compared
There are two main options being compared:
filter()
and then mapping over the remaining elements to extract the desired property using map()
.filter
and map
into a single method.Pros and Cons
Pros:
Cons:
filter
and map
, which can lead to additional overhead due to function call overhead and intermediate array creation.Pros:
Cons:
Library Usage
There is no explicit library usage in the provided benchmark, as both filter
and flatMap
are built-in JavaScript methods. However, it's worth noting that some libraries (e.g., Lodash) may provide additional variants or optimizations for these operations.
Special JS Feature/Syntax
The benchmark uses a feature introduced in ECMAScript 2019: the spread operator (...
) in the context of flatMap
. This is used to expand the array into individual elements, allowing for more concise syntax. The use of this feature indicates that the benchmark is designed to take advantage of modern JavaScript features.
Other Considerations
Alternatives
If you need to compare other methods or optimize these operations further, consider exploring:
reduce()
instead of map
or flatMap
.Keep in mind that the specific optimization approach will depend on your use case, dataset size, and target browser support.