Tuesday, August 20, 2013

for..in vs. Object.keys performance in JavaScript

For those curious, you may debate if the JavaScript for..in loop is faster than creating an array via Object.keys and iterating over that array.

Take an object with 26 attributes:

var attrs = {"a":1,"b":2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26}

Now run this code in a browser (non-IE would be best):

// Loop #1
var date = (new Date()).getTime();
for (var i = 0; i < 100000; ++i)
{
  for (var attr in attrs)
  {
    var num=attrs[attr];
  }
};
var endDate = (new Date()).getTime();
console.log(endDate - date);

// Loop #2
date = (new Date()).getTime();
for (var i = 0; i < 100000; ++i)
{
  var keys = Object.keys(attrs);
  for (var k=0, ksize = keys.length; k < ksize; ++k)
  {
    var num=attrs[keys[k]];
  }
};
endDate = (new Date()).getTime();
console.log(endDate - date);

In Chrome on a Mac, the first loop takes about 2000-3000ms and the second loop 4000-5000ms. In Safari on a Mac, it will take 500-1000ms for the first loop and 1000-2000ms for the second loop. Obviously the code above could be improved for loop #2 if the "var keys..." was outside of the outer for loop, but this test is to simulate a real app where the objects being iterated over would change and not always be the same. The conclusion is simply that for..in is about twice as fast as using Object.keys and iterating over the resulting array.