Ad
  • Custom User Avatar

    As usual, there are lots of caveats with these "benchmarks":

    • The loop body of the test is trivial, which is unrealistic and does not reflect normal use of iteration. You don't iterate thousands of times for trivial things that doesn't even spend as much time as the looping process itself.
    • So, the purpose of the test is to see how fast the iteration process itself does. forEach is designed to also handle array holes, and this check will make things slower.
    • As mentioned above, forEach skips array holes while for loop doesn't. IIRC reduce, which doesn't handle array holes like for loop does, is as fast as for loops
    • Finally, the loop iteration is very, very fast; you can iterate through more than 10^8 times in a second. Are you really sure you need to iterate through something this many times? And are you sure this is really the bottleneck? Because unless you're writing high performance JS (in which case you probably shouldn't be using JS :P), it's just premature optimization. You can optimize things somewhere else, and you'll get much better results for the same amount of effort.
  • Custom User Avatar

    Just read from a performance benchmark test that the normal for loop performs much faster. https://jsperf.com/for-vs-foreach