Javascript for..in vs for loop performance

Look at what’s happening differently in each iteration:

for( var i = 0; i < p1.length; i++ ) 
  1. Check if i < p1.length
  2. Increment i by one

Very simple and fast.

Now look at what’s happening in each iteration for this:

for( var i in p1 )

Repeat

  1. Let P be the name of the next property of obj whose [[Enumerable]] attribute is true. If there is no such property, return (normal, V,
    empty).

It has to find next property in the object that is enumerable. With your array you know that this can be achieved by a simple integer increment, where as the algorithm to find next enumerable is most likely not that simple because it has to work on arbitrary object and its prototype chain keys.

Leave a Comment