This is the Bocoup web log with posts from Al, Ben, Boaz, Darius, Greg, Irene, John, Mike, Nate, Nick, Pete, Richard, Rick, Sam, Sam Clearman, Scott and Tim. You should also make sure to checkout code.bocoup.com, where we keep the finished versions of ideas we kick around here.



Mar 11, 2010

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:




Please send your questions to this address or call Bocoup at 617-379-2752.
This web page is proudly maintained by Bocoup and hosted by (mt) Media Temple.
All code on this website is Open Source. Want to work at Bocoup? Then Apply.
HTML5 Powered with Connectivity / Realtime, CSS3 / Styling, Device Access, Graphics, 3D & Effects, Multimedia, Performance & Integration, Semantics, and Offline & Storage