Closed coffeeandwork closed 3 weeks ago
Hi @coffeeandwork , there are something wrong here, I published a js perf here (https://jsperf.app/tecele) and got some results. I always understood that the native for loop is the fastest but, why these results? For me it's ok to change to native for loop too (but this is strange).
I believe that modern browsers can do some performance trick here. πͺ
I think it's more likely that the console.log()
is computationally expensive and is overshadowing the relatively smaller difference in the performance of forEach
vs native for-loop. I have modified your jsperf slight and I was able to get a consistent result of the native for-loop being way faster than forEach
: https://jsperf.app/tecele/2 Let me know if you are seeing something different.
Nice!
To be fair I removed all content inside loop. The forEach is 15x slower than others. Seems good to change it. The best perfomance isn't the most readable, but it's ok.
In this benchmark I have tested various looping constructs: https://jsbench.me/dulu7atajk/4.
forEach()
appears slower by an order of magnitude compared to a native for-loop. This makes sense because for each iteration insideforEach()
we are doing a callback invocation that comes with its extra costs that we don't incur with a native for loop.