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);
}
arr.filter(o => o.assigned).map(o => o.name)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
flatMap | |
reduce with push | |
loop with push | |
Filtermap |
Test name | Executions per second |
---|---|
flatMap | 2404.1 Ops/sec |
reduce with push | 22659.1 Ops/sec |
loop with push | 30287.9 Ops/sec |
Filtermap | 20122.3 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare the performance of four different approaches:
flatMap
reduce
with a push statementpush
inside a for...of
loopfilter
and map
All tests involve an array of objects, where each object has two properties: name
(a string) and assigned
(a boolean). The assigned
property is used to filter out objects.
Library Used
The benchmark uses the JavaScript Array.prototype.flatMap
, Array.prototype.reduce
, and Array.prototype.filter
methods, as well as the for...of
loop. No external libraries are required for this benchmark.
Special JS Features/Syntax
None of the test cases explicitly use any special JavaScript features or syntax that would require additional explanation.
Benchmark Preparation Code
The preparation code creates an array of 10,000 objects using Array.from
, where each object has a unique name
and a random assigned
property (either true or false). This creates a large dataset for the benchmark.
Test Cases Explanation
Here's a brief overview of what's being tested in each test case:
assigned
is false.reduce
method to iterate over the array, accumulating an array a
with the name
properties of the assigned
objects. The push
statement is used inside the callback function.for...of
loop and pushes the name
property onto an array a
for each assigned
object.filter
and map
methods to create a new array with only the objects where assigned
is true, and then maps over that filtered array to get an array of name
properties.Pros and Cons
Here's a brief summary of the pros and cons for each approach:
for...of
loop and pushes elements onto an array.Alternatives
Some alternative approaches that could have been tested include:
filter
and map
separately: arr.filter(o => o.assigned).map(o => o.name)
reduceRight
or forEach
: arr.reduceRight((a, o) => a.concat([o.name]), [])
for (let i = 0; i < arr.length; i++) { if (arr[i].assigned) result.push(arr[i].name); }
However, these alternatives would likely have similar performance characteristics to the original methods tested in this benchmark.