// 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(function(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) | 514073.5 Ops/sec |
for loop | 795703.6 Ops/sec |
forEach | 488203.6 Ops/sec |
reduce | 592101.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Definition
The provided JSON represents a benchmark that compares three different approaches to summing an array of 1000 random integers: Array.prototype.reduce
, for
loop, and Array.prototype.forEach
.
Options Compared
doRedeuce(pArray, start)
: A traditional reducer function that takes an accumulator and a current value as arguments.doRedeuceArrowFunc(pArray, start)
: An arrow function-based reducer that uses the same logic as the traditional version but with a more concise syntax.for
loop to iterate over the array and accumulate the values.Pros and Cons
doRedeuceArrowFunc
)i < array.length
instead of i >= 0
)Library: Array.prototype.reduce()
The reduce()
method is a built-in JavaScript method that applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. It's commonly used for tasks like summing arrays or aggregating data.
Special JS feature: Arrow functions
Arrow functions (() => { }
) are a concise syntax introduced in ECMAScript 2015. They allow defining small, one-line functions without the function
keyword. In this benchmark, arrow functions are used to implement the doRedeuceArrowFunc
reducer function.
Other Considerations
Math.random()
generates random integers for the array, which may affect performance due to the overhead of generating random numbers.Alternatives
If you're looking for alternative approaches or libraries, consider:
reduce()
and others.reduce()
function and other useful tools.for
loops or while
loops.Keep in mind that the performance differences between these approaches may be small, depending on the specific use case and input data.