Created
May 16, 2012 20:20
-
-
Save codejoust/2713636 to your computer and use it in GitHub Desktop.
benchmark_for_in
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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