var arrRandom = [];
var reduceResult = forEachResult = forLoopResult = 0;
for(var intCtr=0; intCtr<1000; intCtr++) {
arrRandom.push(Math.floor(Math.random() * Math.floor(100)));
}
reduceResult = arrRandom.reduce(function(accum, curr) {return accum+curr});
arrRandom.forEach(function (item) { return forEachResult += item;})
for(var intCtr=0; intCtr<arrRandom.length; intCtr++) { forLoopResult += arrRandom[intCtr] }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
forEach | |
for loop |
Test name | Executions per second |
---|---|
reduce | 972522.8 Ops/sec |
forEach | 2871.9 Ops/sec |
for loop | 1714.3 Ops/sec |
The provided JSON represents a JavaScript benchmark test case on MeasureThat.net, which compares the performance of three different approaches for summing an array of random numbers: forEach
, for
loop, and reduce
.
What is tested?
The tests measure the execution time (in seconds) of each approach to sum up 1,000 random numbers generated within a specified range. The random number generation is performed in a separate preparation code section.
Options compared
forEachResult
) within the callback.for
loop is used to iterate over the array and sum up its elements. This approach involves explicit looping and indexing into the array.reduce()
method applies a user-supplied function (reducer) to each element in the array, accumulating a value (reduceResult
) that is returned as the final output of the operation.Pros and cons of each approach
forEach
does not provide direct access to the array elements or their indices.reduce()
.Library and syntax
The provided benchmark uses standard JavaScript APIs (forEach
, for
loop, reduce
) that are part of the ECMAScript specification. No external libraries or frameworks are used.
Special JS feature or syntax
There is no explicit mention of any special JavaScript features or syntax in the provided benchmark. However, it's worth noting that the use of reduce()
might be considered a more modern and concise approach to this problem.
Other alternatives
If you were to rewrite these benchmarks using alternative approaches (or languages), some possible options could include:
map()
instead of forEach
: Since map()
returns an array, it would require additional processing steps to accumulate the values.Array.prototype.reduceRight()
: This method can reduce the number of iterations required for large arrays.