// Create an array of 1000 random intergers between 1 and 10000
var arrRandom = [];
for(var intCtr=0; intCtr<1000; intCtr++) {
arrRandom.push(Math.floor(Math.random() * Math.floor(10000)));
}
function doRedeuce(pArray) {
return pArray.reduce(function(accum, curr) { return accum += curr; });
}
function doRedeuceArrowFunc(pArray) {
return pArray.reduce((accum, curr) => accum += curr);
}
function doLoop(pArray) {
var accum = 0;
const l = pArray.length
for(var intCtr=0; intCtr<l; intCtr++) {
accum += pArray[intCtr];
}
return accum;
}
function doForEach(pArray) {
var accum = 0;
pArray.forEach((item) => {
accum += item;
});
}
var reduceResult=0;
redeuceResult = doRedeuceArrowFunc(arrRandom);
var loopResult=0;
loopResult = doLoop(arrRandom);
var forEachResult=0
forEachResult = doForEach(arrRandom)
var reduceResult=0;
redeuceResult = doRedeuce(arrRandom);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Reduce arrow | |
ForLoop | |
ForEach | |
Reduce |
Test name | Executions per second |
---|---|
Reduce arrow | 407708.8 Ops/sec |
ForLoop | 730333.2 Ops/sec |
ForEach | 441646.2 Ops/sec |
Reduce | 340096.0 Ops/sec |
Let's break down the benchmark test cases and explanations.
Benchmark Test Cases
The provided benchmark test cases measure the performance of three different approaches to reduce an array of integers: doRedeuce
, doRedeuceArrowFunc
, doLoop
, and doForEach
.
intCtr
) to iterate over the array and accumulate the sum.intCtr
) to iterate over the array and accumulate the sum.forEach
method, which calls a provided callback function once for each element in the array, to perform the reduction operation.Comparison of Options
Here's a comparison of the four options:
doRedeuceArrowFunc
approach tends to be the fastest, followed by doLoop
, then doForEach
, and finally doRedeuce
.doLoop
approach is the most readable, as it uses a traditional loop with clear variable names.doForEach
approach is the least reusable, as it relies on the specific implementation of the forEach
method, which may vary across browsers or versions.Libraries and Special Features
The test cases use no external libraries. However, they do utilize some special JavaScript features:
doRedeuceArrowFunc
to define a concise reduction operation.forEach
method usage.Other Considerations
Alternatives
Other alternatives for reducing arrays in JavaScript include:
Array.prototype.reduce()
with a traditional callback function: arrRandom.reduce(function(accum, curr) { return accum + curr; }, 0)
Promise.all()
or Map
reductionsKeep in mind that the performance results may vary depending on the specific use case and requirements.