Created
October 5, 2014 05:56
-
-
Save magicdawn/d33604c651189267812c to your computer and use it in GitHub Desktop.
test Object#hash
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
Object.prototype.hash1 = function(string) { | |
var code = "try{ return this."+ string +" } catch(e){ return undefined }" | |
return (new Function(code)).call(this); | |
}; | |
var test = { | |
'a':{ | |
'b':{ | |
'c':{ | |
'd':10 | |
} | |
} | |
} | |
} | |
console.time("Object#hash new Function") | |
console.log(test.hash1('a.b.c.d')); | |
for (var i = 0; i < 100000; i++) { // 10w 次 | |
test.hash1('a.b.c.d') | |
}; | |
console.timeEnd("Object#hash new Function") | |
Object.prototype.hash2 = function(str) { | |
// hash() | |
if(!str) return this; | |
if(typeof str === 'string') | |
str = str.split('.') | |
var ret = this[str[0]]; | |
if(str.length === 1){ | |
return ret | |
} | |
else{ | |
return ret | |
? ret.hash2(str.slice(1)) | |
: ret | |
} | |
} | |
console.time("Object#hash recursive") | |
console.log(test.hash2('a.b.c.d')); | |
for (var i = 0; i < 100000; i++) { // 10w 次 | |
test.hash2('a.b.c.d') | |
} | |
console.timeEnd("Object#hash recursive") | |
var ettr = require('ettr'); | |
Object.prototype.hash3 = function(str) { | |
return ettr.get(this,str) | |
}; | |
console.time("Object#hash ettr") | |
console.log(test.hash3('a.b.c.d')); | |
for (var i = 0; i < 100000; i++) { // 10w 次 | |
test.hash3('a.b.c.d') | |
}; | |
console.timeEnd("Object#hash ettr") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment