// 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 reduceCallback(accum, curr) {
return accum+curr;
}
function doRedeuce(pArray) {
return pArray.reduce(reduceCallback);
}
function doLoop(pArray) {
var accum = 0;
for(var intCtr=0; intCtr<pArray.length; intCtr++) {
accum += pArray[intCtr];
}
return accum;
}
function decrWhile(pArray) {
var accum = 0;
var index = pArray.length;
while(index--) {
accum += pArray[index];
}
return accum;
}
function doForEach(pArray) {
var accum = 0;
pArray.forEach(function(item) {
accum += item;
});
}
var redeuceResult=0;
redeuceResult = doRedeuce(arrRandom);
var loopResult=0;
loopResult = doLoop(arrRandom);
var forEachResult=0
forEachResult = decrWhile(arrRandom)
var decrWhileResult=0;
decrWhileResult = doForEach(arrRandom)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
for loop | |
forEach | |
decrement while |
Test name | Executions per second |
---|---|
reduce | 664961.1 Ops/sec |
for loop | 1255454.0 Ops/sec |
forEach | 755513.2 Ops/sec |
decrement while | 253727.5 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The test measures the performance of four different approaches to summing 1000 random numbers:
Array.reduce()
Array.forEach()
(with a custom decrementing index)Approach 1: Array.reduce()
Array.reduce()
is a built-in JavaScript function that reduces an array to a single value by applying a callback function to each element in the array. In this case, the callback function simply adds the current number to the accumulator.
Pros:
Cons:
Approach 2: For Loop
A traditional for loop iterates over the elements of an array, executing a block of code for each element.
Pros:
Cons:
Approach 3: Array.forEach()
Array.forEach()
is another built-in JavaScript function that executes a callback function for each element in an array. In this case, the callback function adds the current number to the accumulator.
Pros:
Array.reduce()
, but with a more concise syntaxArray.reduce()
due to optimized iterator implementationCons:
Approach 4: Custom "Decrement While" Loop
This custom loop uses a decrementing index to access elements in the array, similar to a traditional for loop.
Pros:
Cons:
Library Used
None explicitly mentioned, but Math.random()
is used to generate random numbers.
Special JS Features/Syntax
None explicitly mentioned.
Alternative Approaches
Other approaches that could be tested include:
Array.prototype.map()
with a callback functionArray.prototype.every()
or Array.prototype.some()
with a callback functionNote that these alternatives may not provide significant performance improvements over the existing approaches and would require additional benchmarking to confirm.