var arr = Array(10_000).fill({arr: [0,1]})
arr.reduce((acc, x) => {acc.push(x.arr); return acc}, [])
arr.flatMap(x => x.arr)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce with concat | |
flatMap |
Test name | Executions per second |
---|---|
reduce with concat | 5296.3 Ops/sec |
flatMap | 377.9 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The test compares two approaches: using reduce()
with concat
(or equivalently, .push()
) versus using flatMap()
on an array of arrays.
Script Preparation Code
var arr = Array(10_000).fill({arr: [0,1]});
This code creates a large array (arr
) containing 10,000 objects, each with an arr
property that contains two elements: [0, 1]
.
Benchmark Definitions
There are two benchmark definitions:
arr.reduce((acc, x) => { acc.push(...x.arr); return acc }, []);
This code uses the reduce()
method to iterate over the array and push each element of the nested arrays into a new array (acc
). The resulting array is then returned.
arr.flatMap(x => x.arr);
This code uses the flatMap()
method, which is a more modern replacement for .concat()
with .map()
. It returns a new array with the elements of each nested array, without creating intermediate arrays.
Library and Special Features
In this benchmark, we're using JavaScript's built-in Array methods:
.reduce()
.flatMap()
.push()
No external libraries are used in this test.
Approach Comparison
The two approaches have different performance characteristics:
flatMap()
to perform similarly to .concat()
, so the performance difference may be smaller than expected.Pros and Cons
Other Considerations
When choosing between these approaches, consider the following:
reduce()
might be a better choice due to its simplicity.flatMap()
, this method may be a better option.Alternatives
Other methods for flattening arrays include:
.map()
: arr.map(x => x.arr).flat().forEach()
: arr.forEach(x => { const result = [...x.arr]; // do something with result });for
and array indexing