var arr = Array(10_000).fill(0)
arr.flatMap((x) => [x, x])
arr.map((x) => [x, x]).flat()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
flatmap | |
map+flat |
Test name | Executions per second |
---|---|
flatmap | 4218.6 Ops/sec |
map+flat | 3396.9 Ops/sec |
Let's break down what's being tested on the provided JSON and explain the different approaches, pros and cons.
Benchmark Definition
The benchmark is comparing two approaches to flatten an array of arrays: flatMap
vs map + flat
. This means we're testing how efficient JavaScript engines perform these operations on a large array (10,000
elements) in a loop.
Script Preparation Code
The script preparation code creates an array with 10,000 zeros using the Array
constructor. This is done to ensure consistent input data for both test cases.
Html Preparation Code
There's no HTML preparation code provided, which means we can assume that any necessary setup or cleanup is handled by the JavaScript engine itself.
Individual Test Cases
We have two individual test cases:
flatMap
method on an array of arrays.map
and flat
methods to achieve the same result as flatMap
.Library Used
Both flatMap
and map
methods are part of the Array prototype in JavaScript, which is why they're not explicitly mentioned as libraries.
Special JS Feature or Syntax
None of these test cases use special JavaScript features like async/await, generators, or functional programming constructs beyond basic array methods. They rely solely on standard JavaScript syntax.
Pros and Cons of Approaches
flatMap
method call, reducing potential overhead.map
followed by flat
) and can lead to slightly less readable code.In general, flatMap
is often preferred for its readability and simplicity. However, if performance is a concern, using map+flat
might be a better choice.
Alternative Approaches
Other ways to flatten an array of arrays include:
[...array]
) or Array.prototype.reduce()
._.flatten()
).However, these alternatives may not always offer significant performance benefits over the built-in flatMap
and map+flat
methods.
Benchmark Results
The latest benchmark results show Firefox 131 performing better for flatMap
, with an execution rate of 3586.893310546875 executions per second, compared to 2485.316162109375 for map+flat
. This suggests that the built-in flatMap
method might be optimized for performance in this specific scenario.
Keep in mind that benchmark results can vary depending on the JavaScript engine, hardware, and other factors. These results are likely a snapshot of a particular environment and may not reflect real-world performance differences.