var arr = Array(10_000).fill(0)
arr.reduce((acc, item) => { acc.push(item, item); return acc; }, []);
arr.flatMap((item) => [item, item])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Reduce | |
FlatMap |
Test name | Executions per second |
---|---|
Reduce | 12532.4 Ops/sec |
FlatMap | 376.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is being tested?
The provided benchmark compares the performance of two JavaScript functions: reduce()
and flatMap()
. Both functions are used to process an array of values, but they differ in how they handle the elements.
In this case, we're testing the two functions with a specific input: an array filled with 10,000 zeros (var arr = Array(10_000).fill(0)
).
Options compared
The benchmark is comparing the performance of reduce()
and flatMap()
. Here's what each function does:
reduce()
: This function applies a callback function to each element in the array, accumulating a result value. In this case, the callback function pushes each element twice (item => { acc.push(item, item); return acc; }
), effectively doubling the number of elements.flatMap()
: This function returns a new array containing the results of applying a provided function on every element in the calling array. In this case, the function simply returns an array with each element duplicated ((item) => [item, item]
).Pros and cons of each approach
acc
).reduce()
might not be suitable due to potential performance and memory issues.In general, if you need to perform a simple aggregation or transformation on a small array, reduce()
might be a better choice. However, when dealing with larger arrays or requiring more flexibility in handling multiple values per element, flatMap()
is likely a better option.
Library used
Neither of the benchmarked functions uses an external library, so no libraries are compared or considered as alternatives.
Special JavaScript feature or syntax
There's no special JavaScript feature or syntax being used in this benchmark. The focus is solely on comparing the performance of two native JavaScript functions: reduce()
and flatMap()
.