// 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 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 = doForEach(arrRandom)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
for loop | |
forEach |
Test name | Executions per second |
---|---|
reduce | 510353.0 Ops/sec |
for loop | 996292.5 Ops/sec |
forEach | 138823.5 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The benchmark is comparing three different approaches to sum an array of 1000 random numbers:
Array.reduce()
: A method that applies a reduction function to each element in the array, accumulating the result.for
loop: A traditional loop that iterates over the array, adding each element to a running total.Array.forEach()
: A method that calls a provided callback function for each element in the array.Options being compared
The three options are being compared in terms of their performance (measured by "ExecutionsPerSecond") on a specific browser and device platform combination.
Pros and Cons
Array.reduce()
: This approach is concise and can be more memory-efficient than traditional loops, as it only requires a single accumulator variable. However, it may not be suitable for very large arrays or performance-critical applications.for
loop: This approach is straightforward and easy to understand, but it can be slower and more memory-intensive than Array.reduce()
, especially for large arrays.Array.forEach()
: This approach is similar to the traditional loop, but it's often considered more elegant and easier to read. However, it may not be as performant as the other two options.Library usage
The benchmark uses the following libraries:
Math.random()
function is used for generating random numbers.Special JS features/syntax
There's no special JavaScript feature or syntax being tested in this benchmark. The code uses standard JavaScript syntax and built-in functions.
Other alternatives
If you're interested in exploring alternative approaches, consider the following:
Array.prototype.every()
or Array.prototype.some()
instead of forEach()
, which can provide similar results but with different performance characteristics.Keep in mind that these alternatives may require significant changes to the benchmark code and might not be suitable for all use cases.