var arr = [];
for (let i = 0; i < 100; i++) {
let internal = [];
for (let j = 0; j < 100; j++) {
internal.push(i * 100 + j);
}
arr.push(internal);
}
let flattened = [];
for (let i = 0; i < arr.length; i++) {
let internal = arr[i];
for (let j = 0; j < internal.length; j++) {
flattened.push(internal[j]);
}
}
let flattened = arr.reduce((acc, i) => [ acc, i], []);
let flattened = arr.reduce((acc, i) => acc.concat(i), []);
let flattened = arr.reduce((acc, i) => {
i.forEach(e => acc.push(e));
return acc;
}, []);
let flattend = arr.flat();
let flattend = arr.flatMap((x) => (x));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
iterate / push | |
reduce / spread | |
reduce / concat | |
reduce / push | |
array.flat | |
frray.flatMap |
Test name | Executions per second |
---|---|
iterate / push | 26001.8 Ops/sec |
reduce / spread | 3137.3 Ops/sec |
reduce / concat | 7820.8 Ops/sec |
reduce / push | 29214.8 Ops/sec |
array.flat | 1602.2 Ops/sec |
frray.flatMap | 1592.1 Ops/sec |
I'll break down the benchmark and its test cases to help understand what's being tested.
Benchmark Overview
The Flatten array of array v3
benchmark measures the performance of different methods for flattening an array of arrays in JavaScript.
Test Cases
There are six test cases:
**: This method uses the
Array.prototype.reduce()method with the
spread operator (
...`) to flatten the array.**: Similar to the previous one, but uses
Array.prototype.concat()` instead of the spread operator.**: This method uses the
Array.prototype.flat()` method to flatten the array.Comparison of Methods
The main differences between these methods are:
reduce / spread
and array.flat()
methods tend to be faster due to their use of optimized algorithms.iterate / push
method uses more memory because it creates a new array for each inner array, whereas the other methods flatten the array in place or use iterators to minimize memory allocation.reduce / push
, are more straightforward and easier to understand, while others, like frray.flatMap
, may be less intuitive due to their experimental nature.Other Considerations
frray.flatMap
is not a standard JavaScript method and might be considered experimental or non-standard. It's crucial to ensure that any benchmarking or performance testing includes consideration for browser support and compatibility.Alternatives
If you're interested in exploring alternative methods for flattening arrays, here are a few:
Array.prototype.reduce()
with a custom callback function.Keep in mind that the performance of these alternatives may vary depending on the specific use case and browser support.