var arr = Array(10000).fill(1)
arr.reduce((acc, x, index) => acc.concat(x, index % 2 ? x : []), [])
arr.flatMap((x, index) => [x, index % 2 && x]).filter(Boolean)
arr.reduce((acc, x, index) => { acc.push(x); if(index % 2) { acc.push(x) } return acc; }, [])
arr.reduce((acc, x, index) => index % 2 ? [x,acc] : acc, [])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Reduce concat | |
FlatMap | |
Reduce push | |
Reduce spread |
Test name | Executions per second |
---|---|
Reduce concat | 7.0 Ops/sec |
FlatMap | 2298.1 Ops/sec |
Reduce push | 27183.3 Ops/sec |
Reduce spread | 28.1 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, compared options, pros and cons of each approach, and other considerations.
Benchmark Overview
The benchmark measures the performance difference between four JavaScript methods: concat
, flatMap
, reduce
with spread syntax (...
), and reduce
with push (push
) to build an array. The test case uses a large array of 10,000 elements filled with the value 1.
Benchmark Definition JSON
The benchmark definition provides two types of information:
arr
filled with 10,000 elements using Array(10000).fill(1)
.Individual Test Cases
There are four test cases, each representing a different approach:
arr.reduce((acc, x, index) => acc.concat(x, index % 2 ? x : []), [])
concat
method to append elements to an accumulator array.arr.flatMap((x, index) => [x, index % 2 && x]).filter(Boolean)
flatMap
method to flatten an array of arrays and filters out falsy values.arr.reduce((acc, x, index) => { acc.push(x); if(index % 2) { acc.push(x) } return acc; }, [])
push
method to append elements to an accumulator array.arr.reduce((acc, x, index) => index % 2 ? [x,...acc] : acc, [])
...
) to create a new array and append elements to an accumulator array.Comparison of Approaches
Here's a brief comparison of the approaches:
concat
. Pros: Simple and efficient for small arrays. Cons: Can be slow for large arrays due to repeated concatenation.flatMap
followed by filtering out falsy values. Pros: Efficient for flattening arrays, but may require additional memory allocations.push
. Pros: Simple and efficient, but can lead to slower performance due to repeated push operations.Library Used
There is no explicit library mentioned in the benchmark definition. However, the use of flatMap
and reduce
methods suggests that this benchmark relies on built-in JavaScript features.
Special JS Features or Syntax
The benchmark uses the following special JS feature:
...
): Used to create a new array by spreading elements from an accumulator array into a new array.arr.reduce((acc, x, index) => acc.concat(x, index % 2 ? x : []), [])
.Other Considerations
When interpreting these results:
Alternatives
If you need to measure the performance of similar operations in a different context: