DEV Community

Discussion on: The Most Useful JavaScript Array Methods Explained with Examples

 
alainvanhout profile image
Alain Van Hout • Edited

Interesting performance comparison. It's unfortunate that in the traditional for loop they did not include assigning arr[i] to a variable since that's inherently part of the other two cases.

Thread Thread
 
buphmin profile image
buphmin

I think these may be a bit off. I did a quick test using jsbench.me, with for...i as the baseline fastest: for...of 5% slower, forEach being 35% slower, and map being 45% slower. Note that run to run one may perform faster depending on what the compiler decides to optimize, which means you need to measure many runs and aggregate.

These results also make sense given the difference in how many memory allocations and references have to be made. For...i requires very little in the way of allocations, for of requires an allocation of the value variable, both forEach and map require the allocation of the function reference and the variable. If map or forEach are ever faster than for...i or for...of then it is a specific optimization on that version of the compiler and will likely fall behind once the compiler devs optimize for...i and for...of again.

Thread Thread
 
myogeshchavan97 profile image
Yogesh Chavan

I agree with you, It may depend on compiler optimization. Thanks for the detailed analysis👍