//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 doForLoop(pArray) {
var accum = 0;
var arrLength = pArray.length;
for(var intCtr=0; intCtr<arrLength; intCtr++) {
accum += pArray[intCtr];
}
return accum;
}
function doForOfLoop(pArray) {
var accum = 0;
for(var value of pArray) {
accum += value;
}
return accum;
}
function doForEach(pArray) {
var accum = 0;
pArray.forEach(function(item) {
accum += item;
});
}
var redeuceResult=0;
redeuceResult = doRedeuce(arrRandom);
var loopResult=0;
loopResult = doForLoop(arrRandom);
var forEachResult=0
forEachResult = doForEach(arrRandom)
var forOfResult=0
forOfResult = doForOfLoop(arrRandom)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.reduce | |
for loop | |
Array.forEach | |
for of loop |
Test name | Executions per second |
---|---|
Array.reduce | 96538.7 Ops/sec |
for loop | 757090.4 Ops/sec |
Array.forEach | 644713.8 Ops/sec |
for of loop | 588140.9 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Overview
The test compares the performance of four different approaches to sum an array of 1000 random integers:
Array.prototype.reduce()
for
loopArray.prototype.forEach()
with a callback functionIterator Protocol
(ECMAScript 2020+) implemented for...of
loopEach test case has a separate benchmark definition, which is executed to measure the execution time.
Options Compared
for
loop: A classic way to iterate over an array using a loop variable.for...of
loop: A modern way to iterate over arrays, introduced in ECMAScript 2020+. It's more concise and efficient than traditional loops.Pros and Cons
for
loop:for...of
loop:Library/Features Used
doRedeuce()
, doForLoop()
, and doForEach()
functions use the Array.prototype.reduce()
, traditional for
loop, and Array.prototype.forEach()
methods, respectively.doForOfLoop()
function uses the new Iterator Protocol
(ECMAScript 2020+) implemented for...of
loop.Special JavaScript Features/Syntax
This benchmark does not use any special JavaScript features or syntax other than the ECMAScript 2020+ Iterator Protocol, which is widely supported in modern browsers and Node.js.
Other Alternatives
For this specific test, the alternatives are:
while
loop instead of a traditional for
loop.map()
method to sum all elements in the array (although this would return a new array with summed values).These alternatives might be suitable for different use cases, but for this specific test, the four options mentioned are the most relevant and comparable approaches.