DEV Community

Discussion on: I Use For Loops Almost Always In Javascript

Collapse
 
drmikecrowe profile image
drmikecrowe

So, I've noticed this pattern in my code a lot:

const ary = await Promise.all(...);
for (let elem of ary) {
    ...
}

Knowing that for ... of loops are not as fast, I started using the following construct:

const ary = await Promise.all(...);
while (ary.length) {
    let elem = ary.shift();
    ...
}

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:

Testing vanilla:      4.1ms
Testing lodash:      25.4ms -- 518% slower
Testing es6-for-of:   7.3ms --  78% slower
Testing forEach:      6.1ms --  48% slower
Testing map:          9.2ms -- 125% slower
Testing reverse:      3.4ms --  17% faster
Testing shift:       20.9ms -- 408% slower
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.