var arr = Array(10_000).fill(0)
arr.reduce((acc, x) => [acc, x], [])
arr.reduce((acc, x) => { acc.push(x); return acc; }, [])
arr.flatMap(x => [x])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce with new array | |
reduce with array mutation | |
flatMap |
Test name | Executions per second |
---|---|
reduce with new array | 29.1 Ops/sec |
reduce with array mutation | 34480.6 Ops/sec |
flatMap | 5607.3 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript benchmarking test case on MeasureThat.net. The test measures the performance of three different approaches to reduce an array in JavaScript: reducing an array with new elements, reducing an array by mutating it, and using flatMap
. Each approach is executed multiple times, and the execution speed (in executions per second) is recorded for each browser version.
Options Compared
The three options compared are:
Pros and Cons of Each Approach
Library and Special JS Features
The test uses the Array.prototype.reduce()
method, which is a built-in JavaScript library. The flatMap()
method is also a built-in JavaScript method, introduced in ES6.
No special JavaScript features or syntax are used in this benchmark.
Other Alternatives
If you need to reduce an array in JavaScript, there are other alternatives:
reduceRight()
: Similar to reduce()
, but starts with the last element of the array and iterates from right to left.forEach()
and push()
: You can use a loop with forEach()
to iterate over the array and push elements onto another array using push()
. However, this approach is less efficient than reduce()
or flatMap()
.In summary, the choice of approach depends on your specific use case and performance requirements. If you need to reduce an array in JavaScript, reduce()
with new elements is often a good starting point, followed by flatMap
if you're targeting modern browsers and want concise syntax.