var arr = Array(10_000).fill([0,0,0])
arr.reduce((acc, item) => {
acc.push(item);
return acc;
}, []);
arr.flatMap((item) => {
return item;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
flatmap |
Test name | Executions per second |
---|---|
spread | 3500.9 Ops/sec |
flatmap | 1968.9 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing the performance of two JavaScript array methods: reduce()
with spreading (...
) and flatMap()
. The test case consists of creating an array of 10,000 elements with three zeros each, and then measuring the time taken to execute these arrays using both methods.
Options Compared
There are two options being compared:
arr.reduce((acc, item) => {\r\n acc.push(...item);\r\n return acc;\r\n }, [])
: This method uses reduce()
to iterate over the array and accumulate the results in a new array. The spreading operator (...
) is used to flatten the inner arrays into a single array.arr.flatMap((item) => {\r\n return item;\r\n})
: This method uses flatMap()
to iterate over the array and return a new array with the flattened elements.Pros and Cons
reduce()
with spreading: This approach can be useful when you need to accumulate results in a new array. However, it may not be the most efficient way to flatten an array because of the overhead of creating a new array.flatMap()
: This approach is specifically designed for flattening arrays and is more efficient than using reduce()
with spreading.However, flatMap()
can also lead to performance issues if the input array is large due to its nature of creating a new array on every execution.
Library and Purpose
Neither of these methods rely on any external libraries. They are built-in JavaScript functions.
Special JS Feature or Syntax
There are no special JavaScript features or syntax mentioned in this benchmark. The code only uses standard JavaScript syntax.
Alternatives
Other alternatives for flattening arrays include using Array.prototype.flat()
(available in modern browsers and Node.js) or creating a custom function to achieve the same result.
// Using flat()
arr.flatMap(item => item).forEach(console.log);
// Custom implementation
function flatten(arr, result = []) {
arr.forEach(item => {
if (Array.isArray(item)) {
flatten(item, result);
} else {
result.push(item);
}
});
return result;
}
flatten(arr);
Keep in mind that the flat()
method has some limitations, such as only flattening two levels deep by default. The custom implementation provides more control over the flattening process.
Overall, this benchmark is useful for comparing the performance of different array methods in JavaScript and helping developers make informed decisions about which approach to use depending on their specific requirements.