This is the bocoup web log with posts from Al, Boaz, Rick, Sam, Nate, Nick & Pete. 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:

2 Trackbacks

  1. [...] See the rest here:  Quickest Loop Through an Object – Quickest Loop Through an Object … [...]

  2. [...] Read more here: Quickest Loop Through an Object – Quickest Loop Through an Object … [...]




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