Let's explore a JavaScript performance test:
const iterations = new Array(10 ** 7);
var x = 0;
var i = iterations.length + 1;
console.time('negative');
while (--i) {
x += iterations[-i];
}
console.timeEnd('negative');
var y = 0;
var j = iterations.length;
console.time('positive');
while (j--) {
y += iterations[j];
}
console.timeEnd('positive');
The initial loop goes from 10,000,000 to 1 and accesses an array of that size using negative indexes. This loops through the array in sequential order.
Contrastingly, the second loop counts down from 9,999,999 to 0 while accessing the same array with positive indexes, essentially going through the array reverse order.
In my experience, the first loop takes more than 6 seconds to finish, whereas the second one completes in just around ~400ms.
What could be causing this speed discrepancy between the two loops?