How to Iterate Over Javascript Arrays - Performance Comparison


This article compares three different ways to iterate over a javascript array and compares the performance of each approach.

Technique 1 :  For Loop

For loop is a common semantic available in most of the languages to repeat the same set of instructions till a certain condition is satisfied. This concept can be used to traverse over the arrays in javascript.

Technique 2 : For In

For in statement can be used to iterate over all the enumerable properties of javascript Arrays and Objects. Order is not guaranteed in this technique.


What are Enumerable Properties?
Properties created via simple assignment or via a property initializer


Technique 3 : For of

Unlike for in, for of works only with the iterable objects of javascript. Arrays, Maps, Sets and Strings(treated as a char array) are some of the iterable objects available in Javascript. Unlike for in, order of the elements is guaranteed in for of.


Technique 4 : forEach

Being a function call, this semantic of this technique is entirely different from previous techniques. Although this technique is more convenient to use, it comes with additional performance overheads and it lacks some capabilities of previous technique such as breaking at the middle.


Performance Comparison

Below script was used to compare the performance of above techniques. This scripts takes the average time to perform 100 iterations over arrays of 1 million length.

Results
RankTechniqueAverage Time(ms)
1For loop24.84
2For of36.44
3forEach58.45
4for in153.71

Chart below gives a better comparison overview of the techniques.
Based on above results, the winner or the fastest technique to iterate over Javascript Arrays is the traditional for loop! However given the convenience, for use cases where performance is not critical, I would still use forEach.

Comments