<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var params = [[1, 2], ["hello", true, 7], [null, undefined, {}], [1, 2, 3, 4, 5], [false, true, {}, {}, {}]];
params.flat();
params.reduce((acc, val) => acc.concat(val), []);
params.reduce((acc, curr) => [acc, curr], []);
params.reduce((acc, curr) => (acc.push(curr), acc), []);
_.flatten(params)
[
params[0],
params[1],
params[2],
params[3],
params[4]
]
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.flat | |
reduce + concat | |
reduce + destructure | |
reduce + push | |
lodash.flatten | |
destructuring |
Test name | Executions per second |
---|---|
Array.flat | 4080629.2 Ops/sec |
reduce + concat | 4387020.5 Ops/sec |
reduce + destructure | 1140487.8 Ops/sec |
reduce + push | 1415444.5 Ops/sec |
lodash.flatten | 11986697.0 Ops/sec |
destructuring | 8094135.0 Ops/sec |
Let's break down what is being tested in the provided JSON.
Benchmark Description
The benchmark measures the performance of different approaches to flatten an array of arrays. The test case uses an array params
that contains multiple sub-arrays with various data types, including numbers, strings, booleans, null, undefined, and objects.
Options Compared
The benchmark compares six different approaches:
reduce()
method to concatenate sub-arrays using the concat()
method.reduce()
method and destructuring syntax (...
) to flatten the sub-arrays.reduce()
method and pushing elements onto an array using the push()
method.flatten()
function to flatten the arrays....
) to flatten the sub-arrays.Pros and Cons of Each Approach
Array.flat()
with added flexibility.Array.flat()
.Special JS Features
The benchmark uses the spread operator (...
) in some test cases, which is a modern JavaScript feature introduced in ECMAScript 2018. This syntax allows for concise and expressive array flattening.
Other Considerations
Alternative Approaches
Some alternative approaches that are not tested in this benchmark include:
map()
instead of reduce()
Array.prototype.flat.call()
instead of Array.prototype.flat()
Note that these alternatives may offer different trade-offs in terms of performance, flexibility, and memory usage.