var a = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
const result = [];
for (const item of a) result.push(item);
const result = a.reduce((flat, el) => [flat, el], []);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
reduce |
Test name | Executions per second |
---|---|
for | 4827038.0 Ops/sec |
reduce | 3095272.5 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches to flatten an array of arrays: using for
loop and using Array.prototype.reduce()
method.
Approaches Compared
for
loop to iterate over each inner array and push its elements into a result array.reduce()
method of the Array
prototype, which applies a callback function to each element in the array, accumulating a value that is returned as the final output.Pros and Cons
reduce()
for large arrays due to the overhead of the loop control flow and potential array concatenation issues.Other Considerations
reduce()
method requires an initial value for the accumulator, which in this case is initialized as an empty array ([]
).Library and Special Features
There is no external library used in these benchmarks.
No special JavaScript features or syntax are being tested here. Both approaches use only standard JavaScript features.
Alternatives
If you need to flatten arrays of arrays, other approaches you might consider include:
Array.prototype.forEach()
method with a callback functionArray.prototype.map()
method (although it would return an array of arrays instead of a single array)flatten
functionKeep in mind that the choice of approach depends on your specific use case, performance requirements, and personal preference.