Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
Stelian
(version: 0)
Comparing performance of:
Reduce vs FlatMap
Created:
4 years ago
by:
Guest
Jump to the latest result
Script Preparation code:
var arr = Array(10_000).fill(0)
Tests:
Reduce
arr.reduce((acc, x) => {acc.push(x); acc.push(x); return acc}, [])
FlatMap
arr.flatMap(x => [x, x])
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
Reduce
FlatMap
Fastest:
N/A
Slowest:
N/A
Latest run results:
No previous run results
This benchmark does not have any results yet. Be the first one
to run it!
Autogenerated LLM Summary
(model
gemma2:9b
, generated one year ago):
This benchmark compares two ways to double each element in an array of 10,000 zeroes: **Option 1: `reduce`** ```javascript arr.reduce((acc, x) => { acc.push(x); acc.push(x); return acc }, []) ``` - **Explanation:** The `reduce()` method iterates through the array and accumulates results in a new array (`acc`). For each element (`x`), it pushes `x` twice into the accumulator, effectively doubling each value. - **Pros:** Clear syntax, conceptually simple to understand. - **Cons:** Can be less efficient than other methods due to repeated pushing operations within the callback. **Option 2: `flatMap`** ```javascript arr.flatMap(x => [x, x]) ``` - **Explanation:** The `flatMap()` method iterates through the array and applies a transformation function (`x => [x, x]`) to each element. This function returns an array containing the original element twice. `flatMap()` then flattens these nested arrays into a single new array. - **Pros:** More concise syntax, potentially more efficient than `reduce` due to flattening being handled internally. - **Cons:** Might be less familiar to developers who are newer to JavaScript. **Other Considerations:** * **Library Usage:** No external libraries are used in these benchmarks. * **Special JS Features:** This benchmark utilizes standard JavaScript array methods (`reduce`, `flatMap`). **Alternatives:** 1. **`map()` followed by `concat()`:** You could map over the array to double each element and then use `concat()` to combine the results into a single array. This approach might be slightly less efficient than `flatMap`. 2. **For Loop:** A traditional for loop could also achieve this, but it's generally considered less concise and potentially less performant compared to the array methods. Let me know if you have any more questions!
Related benchmarks:
filling
array last element big data
TypedArray fill vs loop
shallow copy of 6M elements array
Clone Array - 08/02/2024
Comments
Confirm delete:
Do you really want to delete benchmark?