Quickest Loop Through an Object

A little experiment to find the fastest for-loop for an object.

Approx. Results:

ARY-INDEX: “for(var i = 0” -> 13ms

OBJ-INDEX: “for(var i = 0” -> 218ms

OBJ-KEY: “for(var i in” -> 975ms

var len = 1000000;


// ARRAY VERSION
var check = 0;
var ary = [];
for( var i = 0, l = len; i < l; i++ ){
  ary[i] = i;
}

var start = new Date().getTime();
for( var i = 0, l = len; i < l; i++ ){
  check+=ary[i];
}
alert( new Date().getTime() - start, check );
/***********/


/* 1 object lookup per iteration */
// OBJ WITH "FOR(VAR I =" LOOKUP
var check = 0;
var obj = {};
for( var i = 0, l = len; i < l; i++ ){
  obj[i] = i;
}

var start = new Date().getTime();
for( var i = 0, l = len; i < l; i++ ){
  check+=obj[i];
}
alert( new Date().getTime() - start, check );
/***********/

/* 2 object lookups per iteration at least */
// OBJ WITH "FOR(VAR I IN" LOOKUP
var check = 0;
var obj = {};
for( var i = 0, l = len; i < l; i++ ){
  obj[i] = i;
}

var start = new Date().getTime();
for( var i in obj ){
  check+=obj[i];
}
alert( new Date().getTime() - start, check );
/***********/

Comments

Contact Us

We'd love to hear from you. Get in touch!

Phone

+1 617-283-2807

Mail

P.O. Box 961436
Boston, MA 02196