// 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) {
accum.push(curr);
return accum;
}
function doRedeuce(pArray) {
return pArray.reduce((arr, item) => {
arr.push(item);
return arr;
}, []);
}
function doLoop(pArray) {
var accum = [];
for(var intCtr=0; intCtr<pArray.length; intCtr++) {
accum.push(pArray[intCtr]);
}
return accum;
}
function doForEach(pArray) {
var accum = [];
pArray.forEach(function(item) {
accum.push(item)
});
}
var redeuceResult=[];
redeuceResult = doRedeuce(arrRandom);
var forEachResult=[];
forEachResult = doForEach(arrRandom)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
foreach |
Test name | Executions per second |
---|---|
reduce | 251704.8 Ops/sec |
foreach | 253826.8 Ops/sec |
Let's dive into the provided benchmark and explain what's being tested, compared, and considered.
Benchmark Definition JSON
The benchmark definition represents two JavaScript functions: doRedeuce
and doForEach
. Both functions take an array as input and push its elements to a new array. The only difference between the two functions is the way they iterate over the input array:
doRedeuce
: Uses the built-in Array.prototype.reduce()
method, which applies a callback function to each element in the array.doForEach
: Uses the forEach
loop, which iterates over the elements of the array using a provided callback function.Options Compared
The benchmark compares the performance of two different approaches:
Array.prototype.reduce()
method.forEach
loop.Pros and Cons of Each Approach
Library and Syntax
The benchmark does not explicitly use any libraries, but it does rely on built-in JavaScript features like Array.prototype.reduce()
and the forEach
loop.
However, if we were to extend this benchmark to include additional libraries or syntax features, here are some possibilities:
reduce
method is often implemented in Lodash as a separate function (_reduce
). Using Lodash would add an additional layer of abstraction.doRedeuceAsync()
and doForEachAsync()
.Other Considerations
When building this benchmark, consider the following:
Alternatives
Some alternatives to this benchmark include:
benchmarked
library: The benchmarked library provides a more structured approach to building benchmarks, including automatic error handling and better support for multiple browsers. js-benchmark
: The js-benchmark library offers a simple way to compare the performance of different JavaScript functions using a variety of metrics (e.g., execution time, memory usage).