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), [])
{
const a = [];
for (const o of arr) if (o.assigned) a.push(o.name);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
flatMap | |
reduce with push | |
loop with push |
Test name | Executions per second |
---|---|
flatMap | 5917.2 Ops/sec |
reduce with push | 23907.4 Ops/sec |
loop with push | 18354.1 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Overview
The benchmark is designed to compare the performance of three different approaches:
flatMap
reduce with push
loop with push
These approaches are used to filter an array of objects, where each object has a property called "assigned". The goal is to measure which approach is fastest.
Library and Functionality
The benchmark uses the Array.prototype.flatMap
method, which was introduced in ECMAScript 2019 (ES10). The flatMap
method returns a new array with the results of applying the provided function on each element of the original array. In this case, the function is (o) => (o.assigned ? [o.name] : [])
, which filters out objects without the "assigned" property and returns an array of names.
The reduce
method is also used, but with a twist: instead of using the accumulator to store the result, it uses the push
method to append elements to an array. This approach creates a new array, whereas flatMap
modifies the original array in place.
The third approach uses a simple loop with a conditional statement (if (o.assigned)
) to filter out objects without the "assigned" property and push names to an array.
Pros and Cons
Here's a brief summary of the pros and cons of each approach:
flatMap
:reduce with push
:loop with push
:flatMap
due to loop overhead; less efficient than reduce with push
.Other Considerations
The benchmark measures the number of executions per second (ExecutionsPerSecond) for each approach, which provides a rough estimate of performance. Keep in mind that this metric is not necessarily representative of real-world scenarios.
Alternatives
If you were to rewrite these approaches using different JavaScript features or libraries, here are some alternatives:
flatMap
, you could use filter
and then map:arr.filter(o => o.assigned).map(o => o.name)
reduce with push
, you could use the Array.prototype.concat
method to merge arrays:arr.reduce((acc, o) => acc.concat([o.name]), [])
These alternatives might have different performance characteristics depending on the specific use case.
I hope this explanation helps!