Lets say we have an array of 200 000 elements for example... Now we want to iterate it in different ways and check the fastest one. I've heard that if we will save array.length in variable before loop we will reduce execution time, so i tried the code below
let sum = 0
for (let i = 0; i < arr.length; ++i) sum += arr[i]
against
let sum = 0
for (let i = 0, l = arr.length; i < l; ++i) sum += arr[i]
But i got the same result as if in both cases js reads length value just once in the very beginning.
Then i decided to check, what if during loop we will change an array, removing last element.
let sum = 0
for (let i = 0; i < arr.length; ++i) {
sum += arr[i]
if (i === 100) arr.pop()
}
against
let sum = 0
for (let i = 0, l = arr.length; i < l; ++i) {
sum += arr[i]
if (i === 100) arr.pop()
}
So i expected that second case now should work faster because in first case js inevitably should check array.length each time and i was much suprised that it is not works faster but even slower - from 10 to 15 %. For me it is unexplainable. Any ideas?