var array = [];
for (let i = 0 ; i < 10000 ; i++) {
array.push (Math.random () * 100);
}
let sum = 0;
for (let i = array.length - 1 ; i >= 0 ; i--)
sum += array[i];
let sum = 0;
for (let i = 0 ; i < array.length ; 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 |
---|---|
reversed | |
ordered | |
ordered cached |
Test name | Executions per second |
---|---|
reversed | 1595.4 Ops/sec |
ordered | 821.5 Ops/sec |
ordered cached | 1638.9 Ops/sec |
The benchmark outlined by MeasureThat.net focuses on assessing the performance of different methods for summing the elements of an array in JavaScript, particularly how the order of iteration affects execution speed. The specific tests compare two iteration patterns: a "reversed" loop and two "ordered" loops, with one of the ordered tests using a cached length of the array.
Reversed Loop:
let sum = 0;
for (let i = array.length - 1; i >= 0; i--) {
sum += array[i];
}
Ordered Loop:
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
Ordered Cached Loop:
let sum = 0;
let length = array.length;
for (let i = 0; i < length; i++) {
sum += array[i];
}
.reduce()
, which is more expressive but can have performance pitfalls due to potential overhead from function calls.Uint32Array
, Float64Array
, etc.) could yield better performance due to lower memory overhead and faster access speeds.In conclusion, the benchmark investigates crucial aspects of array iteration performance in JavaScript, providing insights into loop constructs and how they can affect execution efficiency. Developers should consider these findings when optimizing for performance in JavaScript applications, particularly with large datasets or in performance-critical sections of code.