Skip to content

Instantly share code, notes, and snippets.

@founddrama
Created December 22, 2010 02:47
Show Gist options
  • Save founddrama/751015 to your computer and use it in GitHub Desktop.
Save founddrama/751015 to your computer and use it in GitHub Desktop.
Curious: which is faster -- resolving an object via eval()? or a look-up in the global namespace?
var __T = null,
__O = {
b: {
j: {
fn: function(){
// just so that we're performing *some* operation
var _2 = 1 + 1;
}
}
}
},
STR = "__O.b.j.fn",
limit = 100000;
function timeIt(fn){
__T = new Date().getTime();
fn();
console.info('time: ' + ((new Date().getTime()) - __T));
__T = null;
}
function asEval(){
for (var i = 0; i < limit; i++) {
var strA = STR.split("."),
fn = strA.pop(),
ns = eval(strA.join("."));
ns[fn]();
}
}
function asResolver(){
for (var i = 0; i < limit; i++) {
var strA = STR.split("."),
fn = strA.pop(),
ns = this;
while (strA.length){
ns = ns[strA.shift()];
}
ns[fn]();
}
}
timeIt(asEval);
timeIt(asResolver);
// Firefox 3.6
// asEval : 698ms
// asResolver : 393ms
// Safari 5.0.3
// asEval : 140ms
// asResolver : 106ms
// Chrome 8.0.5
// asEval : does not finish (!?)
// asResolver : 110ms
// Internet Explorer 8
// asEval : 812ms
// asResolver : 844ms
@founddrama
Copy link
Author

So if you do it 100,000 times... it's almost twice as fast to do the look-up (instead of eval()) in Firefox; meanwhile...:

  • Safari could do it both ways (twice!) in the time it takes Firefox to finish asResolver()
  • Chrome won't even finish asEval()
  • and somehow asEval() just barly edges out the global ns look-up in Internet Explorer 8.

Just goes to show you... you never know what you'll find!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment