Created
December 22, 2010 02:47
-
-
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?
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...:
Just goes to show you... you never know what you'll find!