// 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, start) {
return pArray.reduce(function(accum, curr) { return accum + curr; }, start);
}
function doRedeuceArrowFunc(pArray, start) {
return pArray.reduce((accum, curr) => accum + curr, start);
}
function doLoop(pArray) {
var accum = 0;
for(var intCtr=0; intCtr<pArray.length; intCtr++) {
accum += pArray[intCtr];
}
return accum;
}
function doForEach(pArray) {
var accum = 0;
pArray.forEach((item) => {
accum += item;
});
}
var reduceResult=0;
redeuceResult = doRedeuceArrowFunc(arrRandom, 0);
var loopResult=0;
loopResult = doLoop(arrRandom);
var forEachResult=0
forEachResult = doForEach(arrRandom)
var reduceResult=0;
redeuceResult = doRedeuce(arrRandom, 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce (arrow function) | |
for loop | |
forEach | |
reduce |
Test name | Executions per second |
---|---|
reduce (arrow function) | 52034.0 Ops/sec |
for loop | 563353.2 Ops/sec |
forEach | 55494.8 Ops/sec |
reduce | 52068.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided benchmark compares three different approaches to sum an array of 1000 random integers: Array.reduce
, for
loop, and Array.forEach
. The goal is to determine which approach is the fastest.
Options Compared
for
loop is used to iterate over the array, adding each element to a running total.forEach
method is used to execute an action on each element in the array, in this case, adding the element to a running total.Pros and Cons
Library/Function Used
In this benchmark, Math.floor
is used to generate random integers between 1 and 10000. No external libraries are required.
Special JS Feature/Syntax
None mentioned in the provided code. However, it's worth noting that modern JavaScript supports arrow functions (=>
) which can simplify code and improve readability.
Other Alternatives
If you wanted to include additional approaches, some alternatives could be:
Array.prototype.reduceRight
Keep in mind that these alternatives might not be directly applicable to this specific benchmark.
Benchmark Preparation Code
The provided script preparation code creates an array of 1000 random integers between 1 and 10000, defines three functions (doRedeuce
, doRedeuceArrowFunc
, and doLoop
) for each approach, and initializes variables for the results. The HTML preparation code is empty in this case.
Individual Test Cases
Each test case executes one of the three approaches (reduce, for loop, or forEach) on the generated array, accumulating the sum in a variable.