This post got me wondering how my loop compares, so I tested my way and other loop constructs here. It's interesting how much slower these other loop constructs are. Needless to say, I'm going back to the traditional for loop now!
I used an array of length 1000, and since I'm impatient I cut down LOOPS to 1e5.
Also to be noted is that the 'shift' loop is not equivalent to the others, because it destroys the input array in the process. I dealt with that (and with creating a long array) by setting up
So, I've noticed this pattern in my code a lot:
Knowing that
for ... of
loops are not as fast, I started using the following construct:This post got me wondering how my loop compares, so I tested my way and other loop constructs here. It's interesting how much slower these other loop constructs are. Needless to say, I'm going back to the traditional for loop now!
Here are my simple test results:
I ran your tests on a longer array, and found increasing the array length magnifies the performance advantage of the vanilla for-loop quite a bit:
I used an array of length 1000, and since I'm impatient I cut down LOOPS to 1e5.
Also to be noted is that the 'shift' loop is not equivalent to the others, because it destroys the input array in the process. I dealt with that (and with creating a long array) by setting up
const someNumbers = Array.from({ length: 1000 }, (v, i) => i);
on the top level, and copying it into testArrayShift() on each iteration of the outer loop.
It runs a bit against my intuition that the reverse loop becomes slower on longer arrays -- I expected it to have a (small) performance advantage.
Actually I'm used to writing the reverse loop as
(and that's the version I actually tested)
but again a surprise: your version is actually a bit faster.
Altogether, I guess I'll just stick to vanilla for-loops from now on.
I added
.reduce()
to the test, and on a long array it's only about twice as slow as the vanilla for-loop.