var arr = Array.from({ length: 9999 }, () => [{a: 1, b: 2, c:3 }, {d: 4, e: 5, f: 6}]);
arr.flat();
arr.flatMap(e => e);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
flat() | |
flatMap() |
Test name | Executions per second |
---|---|
flat() | 1807.7 Ops/sec |
flatMap() | 1579.3 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 objects in JavaScript: flat()
vs flatMap()
. The input data is an array of 10,000 objects, each containing multiple properties (a, b, c, d, e, f).
Options Compared
Two options are being compared:
arr.flat()
: This method uses the spread operator (...
) to flatten the array.arr.flatMap(e => e)
: This method uses a callback function to iterate over each object in the array and return a new flattened array.Pros and Cons of Each Approach
flat()
flatMap()
for large datasets, as it uses the spread operator which creates a new arrayflatMap()
flat()
, especially for large datasetsflat()
Library and Special JS Feature
There is no explicit library mentioned in the benchmark. However, both methods are built-in JavaScript methods.
If you're interested in exploring alternative approaches, some options include:
Array.prototype.reduce()
: This method can be used to flatten an array by accumulating the values from each object.lodash.flat()
: If you're using the Lodash library, you can use _.flat()
which is a more concise and readable way to flatten an array.Other Considerations
When writing benchmarks like this one, it's essential to consider factors such as:
In this benchmark, the results indicate that flatMap()
is generally faster than flat()
, especially for large datasets. However, the actual performance difference will depend on the specific use case, dataset size, and platform being tested.