beercss / beercss

Build material design interfaces in record time... without stress for devs... πŸΊπŸ’›
https://www.beercss.com
MIT License
940 stars 47 forks source link

replace forEach() with native for-loops for performance improvement #287

Closed coffeeandwork closed 3 weeks ago

coffeeandwork commented 1 month ago

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 inside forEach() we are doing a callback invocation that comes with its extra costs that we don't incur with a native for loop.

leonardorafael commented 1 month 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).

Chrome 123 (3 runs)

go001 go002 go003

Firefox 124 (3 runs)

ff001 ff002 ff003

leonardorafael commented 1 month ago

I believe that modern browsers can do some performance trick here. πŸͺ„

coffeeandwork commented 1 month ago

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.

leonardorafael commented 1 month ago

Nice!

leonardorafael commented 1 month ago

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.

image