DEV Community

Discussion on: I Use For Loops Almost Always In Javascript

Collapse
 
rjbudzynski profile image
rjbudzynski

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:

Testing vanilla:     120.9ms
Testing lodash:      2561.8ms -- 2019% slower
Testing es6-for-of:  347.6ms -- 188% slower
Testing forEach:     1179.2ms -- 875% slower
Testing map:         1517.9ms -- 1156% slower
Testing reverse:     166.4ms --  38% slower
Testing shift:       7316.3ms -- 5952% slower

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

for (let i = someNumbers.length; i--; ) {
    tmp += someNumbers[i];
}

(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.

Collapse
 
rjbudzynski profile image
rjbudzynski

I added .reduce() to the test, and on a long array it's only about twice as slow as the vanilla for-loop.