Skip to content

Instantly share code, notes, and snippets.

@codejoust
Created May 16, 2012 20:20
Show Gist options
  • Save codejoust/2713636 to your computer and use it in GitHub Desktop.
Save codejoust/2713636 to your computer and use it in GitHub Desktop.
benchmark_for_in
sparks% cat benchmark.js
var obj = {}, num_in = 1000000;
while(num_in--){
obj[(Math.random()*10000).toString()] = Math.random().toString();
}
function time_it(fn_tm){
var start_time = new Date().getTime();
fn_tm();
var end_time = new Date().getTime();
console.log('Task completed in: ' + (end_time - start_time));
}
var obj_array = [];
time_it(function(){
for (key in obj){
obj_array.push(obj[key]);
obj_array.push(key);
}
});
console.log('Test completed w/ ' + obj_array.length);
var obj_array = [];
time_it(function(){
Object.keys(obj).forEach(function(key){
obj_array.push(obj[key]);
obj_array.push(key);
});
});
console.log('Test completed w/ ' + obj_array.length);
var obj_array = [];
time_it(function(){
var keys = Object.keys(obj), i = 0, kl = keys.length;
for (;i<kl;i++){
obj_array.push(obj[keys[i]]);
obj_array.push(keys[i]);
}
});
console.log('Test completed w/ ' + obj_array.length);
console.log('Done');
process.exit();
==== Output:
sparks% node benchmark.js
Task completed in: 969
Test completed w/ 1999766
Task completed in: 618
Test completed w/ 1999766
Task completed in: 5691
Test completed w/ 1999766
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment