var arr = Array(10_000).fill([0,0,0])
[arr]
arr.flatMap((item) => {
return item;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
flatmap |
Test name | Executions per second |
---|---|
spread | 97922.6 Ops/sec |
flatmap | 2024.3 Ops/sec |
I'd be happy to help explain what's being tested in this benchmark.
What is tested?
The provided benchmark measures the performance difference between using the spread operator (...
) and flatMap()
methods on an array of arrays (arr
). The test case consists of two individual tests: "spread" and "flatmap".
Options compared
In the first test ("spread"), the benchmark runs a loop that iterates over each inner array in arr
using the spread operator (...
), like this:
arr.flatMap((item) => {
return item;
});
This is equivalent to using a for-of loop or Array.prototype.forEach() with a callback function.
In the second test ("flatmap"), the benchmark runs a similar loop that iterates over each inner array in arr
using the flatMap()
method, like this:
arr.flatMap((item) => {
return item;
});
Pros and cons of each approach
...
): This approach is concise and readable, as it eliminates the need for a loop or callback function. However, it may incur additional overhead due to the creation of new arrays.flatMap()
method: This approach is also concise and readable, but it uses built-in array method that may be optimized by the engine. Additionally, some older browsers may not support this method.Library and syntax
In both tests, no external libraries are used. The JavaScript syntax itself is being compared.
Special JS feature or syntax
There is no special JavaScript feature or syntax being tested here, as it's just a straightforward comparison of two array methods.
Other alternatives
If you wanted to test this benchmark with alternative approaches, some options could be:
for (const item of arr) {
result.push(...item);
}
arr.forEach((item) => {
result = result.concat(item);
});
Keep in mind that these alternatives might introduce additional overhead or changes to the performance characteristics.
Benchmark preparation code
The provided benchmark preparation code creates an array arr
with 10,000 elements, each containing three zeros. This ensures a large enough dataset for meaningful performance comparisons.
Individual test cases
Each individual test case consists of a single "Benchmark Definition" JSON object that represents the input data for the test. The first test ("spread") and second test ("flatmap") both use the same arr
array as their input, but with different implementation details (i.e., using the spread operator vs. flatMap()
method).
Latest benchmark result
The provided benchmark result shows the execution counts per second for each test case, running on Chrome 122 on a desktop device. The results will likely vary depending on the specific hardware and engine configuration used to run the benchmarks.