var array = [];
for (let i = 0 ; i < 10000 ; i++) {
array.push (Math.random () * 100);
}
let sum = 0;
for (let i = 0 ; i < array.length ; i++)
sum += array[i];
let sum = 0;
for (let i = array.length - 1 ; i >= 0 ; i--)
sum += array[i];
let sum = 0;
let length = array.length;
for (let i = 0 ; i < length ; i++)
sum += array[i];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ordered | |
reversed | |
ordered cached |
Test name | Executions per second |
---|---|
ordered | 807.7 Ops/sec |
reversed | 1630.2 Ops/sec |
ordered cached | 1634.2 Ops/sec |
The benchmark defined in the provided JSON tests the performance of summing up the elements of an array using different loop approaches in JavaScript. Here's a breakdown of the various test cases, their implications, and considerations.
Ordered Loop:
let sum = 0;
for (let i = 0; i < array.length; i++)
sum += array[i];
Reversed Loop:
let sum = 0;
for (let i = array.length - 1; i >= 0; i--)
sum += array[i];
Ordered Cached Loop:
let sum = 0;
let length = array.length;
for (let i = 0; i < length; i++)
sum += array[i];
length
) before entering the loop, thereby avoiding repeated access to array.length
during each iteration.The execution results from the benchmark indicate that:
array.length
in each loop iteration.Language Feature:
The benchmark makes use of the let
keyword introduced in ES6 (ECMAScript 2015). This allows block scoping for the loop variable (i
), which is a more modern syntax compared to the oldest ways of declaring variables using var
. This is advantageous as it prevents variable hoisting issues and reduces the risk of creating unintended global variables.
Alternatives:
Other alternatives for summing an array include:
Using Array.prototype.reduce()
:
const sum = array.reduce((acc, curr) => acc + curr, 0);
Using a for...of
loop:
let sum = 0;
for (const value of array) {
sum += value;
}
Using Array.prototype.forEach()
:
let sum = 0;
array.forEach(value => {
sum += value;
});
.reduce()
, it is clean but may have performance considerations due to the callback function's overhead.The benchmark effectively tests different looping constructs to evaluate their performance in summing values in an array. The choice between these approaches can vary based on the context of use, array size, and performance requirements, demonstrating the importance of understanding both the language capabilities and their impacts on performance.