var arrRandom = [];
for(var intCtr=0; intCtr<1000; intCtr++) {
arrRandom.push(Math.floor(Math.random() * Math.floor(100)));
}
function doRedeuce(pArray) {
return pArray.reduce(function(accum, curr) {return accum+curr});
}
function doLoop(pArray) {
var accum = 0;
for(var intCtr=0; intCtr<pArray.length; intCtr++) {
accum += pArray[intCtr];
}
return accum;
}
var redeuceResult=0;
redeuceResult = doRedeuce(arrRandom);
var loopResult=0;
loopResult = doLoop(arrRandom);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
for loop |
Test name | Executions per second |
---|---|
reduce | 955924.8 Ops/sec |
for loop | 1080904.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition:
The provided JSON represents a benchmark test that compares three approaches for summing up an array of random numbers:
map()
forEach()
for
loopThe benchmark is defined in two parts:
doRedeuce()
(which uses the reduce()
method) and doLoop()
(which uses a traditional for
loop).Options Compared:
The three options being compared are:
map()
forEach()
for
loopPros and Cons of Each Approach:
forEach():
map()
in terms of code length and performancefor
loop, since it creates an event handler for each iterationfor
loop:Library Used:
There is no library used in this benchmark test.
Special JS Feature or Syntax:
None of the options use any special JavaScript features or syntax.
Other Alternatives:
If you want to compare more approaches, some alternatives could be:
Array.prototype.forEach()
instead of forEach()
tail
function (which is similar to reduce()
)Array.prototype.reduceRight()
Note that the choice of alternative options depends on the specific use case and performance requirements.
Benchmark Preparation Code:
Here is the benchmark preparation code in JavaScript:
var arrRandom = [];
for (var intCtr = 0; intCtr < 1000; intCtr++) {
arrRandom.push(Math.floor(Math.random() * Math.floor(100)));
}
function doRedeuce(pArray) {
return pArray.reduce(function (accum, curr) {
return accum + curr;
});
}
function doLoop(pArray) {
var accum = 0;
for (var intCtr = 0; intCtr < pArray.length; intCtr++) {
accum += pArray[intCtr];
}
return accum;
}
And here is the individual test cases:
var redeuceResult = 0;
redeuceResult = doRedeuce(arrRandom);
var loopResult = 0;
loopResult = doLoop(arrRandom);