var arr = Array(10_000_000).fill(0);
arr.flatMap(x => [x, x * 2]);
const n = arr.length;
const acc = new Array(n * 2);
for (let i = 0; i < n; i++){
const x = arr[i];
acc[i * 2] = x;
acc[i * 2 + 1] = x * 2;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
flatMap | |
for loop |
Test name | Executions per second |
---|---|
flatMap | 4.1 Ops/sec |
for loop | 19.7 Ops/sec |
The benchmark presented compares two different approaches for transforming an array in JavaScript: the flatMap
method versus a traditional for
loop.
flatMap Method:
arr.flatMap(x => [x, x * 2]);
flatMap
method creates a new array with each element being the result of a callback function, which in this case generates two elements for each input element (the element itself and twice its value). The results are then flattened into a single array.For Loop:
const n = arr.length;
const acc = new Array(n * 2);
for (let i = 0; i < n; i++) {
const x = arr[i];
acc[i * 2] = x;
acc[i * 2 + 1] = x * 2;
}
for
loop explicitly iterates through each element of the array, populating a new array (acc
) by setting two values for each element (the element and its double), based on index calculations.flatMap Method:
for
loop for more complex logic.For Loop:
for loop
achieving approximately 2.66 executions per second and flatMap
slightly behind at 2.65 executions per second.When considering alternatives for transforming arrays, there are a few other methods in JavaScript:
map + concat: Instead of flatMap
, one could use map
to transform the values and then concat
to merge the resulting arrays, though this would generally be less efficient than flatMap
for flattening.
const result = [].concat(...arr.map(x => [x, x * 2]));
reduce: For flexibility in operations or accumulation, reduce
can also be employed, albeit potentially at the cost of readability.
const result = arr.reduce((acc, x) => {
acc.push(x, x * 2);
return acc;
}, []);
This benchmark demonstrates the performance characteristics of two popular ways to process arrays in JavaScript, giving developers insights into when one method might be preferred over another based on readability, performance, and specific use cases.