// 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.add(curr);
}
function doRedeuce(pArray) {
return pArray.reduce(reduceCallback, new Set());
}
function doLoop(pArray) {
var accum = new Set();
for(const item of pArray) {
accum.add(item);
}
return accum;
}
var redeuceResult=0;
redeuceResult = doRedeuce(arrRandom);
var loopResult=0;
loopResult = doLoop(arrRandom);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
for loop |
Test name | Executions per second |
---|---|
reduce | 48521.2 Ops/sec |
for loop | 52923.6 Ops/sec |
The benchmark described in the provided JSON focuses on comparing two different methods for summing up a set of random integers: using the Array.prototype.reduce()
method versus a for...of
loop. Both methods ultimately aim to accumulate the values from an array into a Set
, which inherently manages unique values.
Array.reduce() Method (doRedeuce
function):
reduce
method of arrays, which takes a callback function and an initial accumulator.reduceCallback
) adds the current number to a Set
, which stores only unique values.For...of Loop (doLoop
function):
for...of
loop construct. Set
, accumulating unique values without needing a separate callback function.Array.reduce()
Pros:
Cons:
For...of Loop
Pros:
Cons:
Set
ensures that only unique values are stored in both methods, which is a key requirement of the task.In this benchmark, no external libraries are utilized; instead, the native Array
and Set
data structures provided by JavaScript are used.
The benchmark predominantly leverages standard JavaScript features:
reduce
method is a built-in array function that allows for accumulation of values through a callback.for...of
is a loop construct introduced in ES6 (ECMAScript 2015) that iterates over iterable objects such as arrays, making it easier to work with collections.Other alternatives for performance comparison could include:
for
Loop: A classic approach that offers potentially better performance, especially in tight loops since there are fewer abstractions.Array.prototype.forEach()
: Similar to reduce
, but designed for executing a function on each element without returning a value, not suitable for accumulating results but an option for iterating over arrays.In summary, this benchmark provides insight into performance differences between two common methods for processing arrays in JavaScript, showcasing the evolving approaches to coding in the language while maintaining core functionality.