var arr = Array.from({length:10000}, (v, i) => ({name: i, assigned: Math.random() < 0.5}));
arr.flatMap((o) => (o.assigned ? [o.name] : []));
arr.reduce((a, o) => (o.assigned && a.push(o.name), a), [])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
flatMap | |
reduce with push |
Test name | Executions per second |
---|---|
flatMap | 4886.7 Ops/sec |
reduce with push | 14433.4 Ops/sec |
Let's break down the provided benchmark definition and analyze what's being tested.
What is tested?
The benchmark compares the performance of two approaches to filter an array in JavaScript:
arr.flatMap((o) => (o.assigned ? [o.name] : []));
- This uses the flatMap()
method, which flattens an array of arrays into a single array.arr.reduce((a, o) => (o.assigned && a.push(o.name), a), [])
- This uses the reduce()
method with a callback function that filters and pushes elements to the accumulator array.Options compared
The benchmark compares two approaches:
flatMap()
to filter and flatten the array.reduce()
with a callback function that filters and pushes elements to the accumulator array.Pros and cons of each approach:
reduce()
method.reduce
for very large arrays, due to the additional overhead of flattening the array.flatMap
.Library and its purpose
Neither of these approaches uses a specific library. They are built-in JavaScript methods that manipulate arrays.
Special JS feature or syntax
There are no special JavaScript features or syntax used in this benchmark.
Other alternatives
For filtering arrays, other alternatives include:
Array.prototype.filter()
:arr.filter((o) => o.assigned).map((o) => o.name);
This approach is similar to the flatMap
method but uses two separate methods instead of one.
const result = [];
for (const o of arr) {
if (o.assigned) {
result.push(o.name);
}
}
This approach is more explicit and verbose than both flatMap
and reduce with push
, but can be useful for understanding the inner workings of array manipulation.
Keep in mind that performance differences between these approaches may not be significant for small arrays, but can become noticeable for very large datasets.