- pure js implementation consistently takes 0ms, whereas
new Function
fluctuates. - manual lookup can also differentiate
undefined
set on the object, and a property not found
Last active
August 25, 2015 19:36
-
-
Save bahamas10/3a6516358d86bcef11c5 to your computer and use it in GitHub Desktop.
dotted lookup performance
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
$ ./dotted-lookup.js a | |
new function begin | |
{ b: { c: 'hello' } } | |
new function end: 1ms | |
manual parsing begin | |
{ b: { c: 'hello' } } | |
manual parsing end: 0ms | |
$ ./dotted-lookup.js a.b | |
new function begin | |
{ c: 'hello' } | |
new function end: 2ms | |
manual parsing begin | |
{ c: 'hello' } | |
manual parsing end: 0ms | |
$ ./dotted-lookup.js a.b.c | |
new function begin | |
'hello' | |
new function end: 0ms | |
manual parsing begin | |
'hello' | |
manual parsing end: 0ms | |
$ ./dotted-lookup.js a.b.c.d | |
new function begin | |
undefined | |
new function end: 1ms | |
manual parsing begin | |
error thrown: no property a.b.c.d found | |
undefined | |
manual parsing end: 0ms |
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
#!/usr/bin/env node | |
/** | |
* script to test dotted lookups | |
* | |
* Author: Dave Eddy <dave@daveeddy.com> | |
* Date: August 25, 2015 | |
* License: MIT | |
*/ | |
var lookup = process.argv[2]; | |
var obj = { | |
a: { | |
b: { | |
c: 'hello' | |
} | |
} | |
}; | |
var o; | |
// new Function | |
console.log('new function begin'); | |
console.time('new function end'); | |
var func = new Function('return this.' + lookup); | |
o = func.call(obj); | |
console.dir(o); | |
console.timeEnd('new function end'); | |
console.log(); | |
// manual parsing | |
console.log('manual parsing begin'); | |
console.time('manual parsing end'); | |
try { | |
o = dottedLookup(obj, lookup); | |
} catch (e) { | |
console.log('error thrown: %s', e.message); | |
} | |
console.dir(o); | |
console.timeEnd('manual parsing end'); | |
/* | |
* lookup the property "str" (given in dot-notation) in the object "obj". | |
* "c" is optional and may be set to any delimiter (defaults to dot: ".") | |
*/ | |
function dottedLookup(obj, str, c) { | |
if (c === undefined) | |
c = '.'; | |
var o = obj; | |
var dots = str.split(c); | |
var s = []; | |
for (var i = 0; i < dots.length; i++) { | |
var dot = dots[i]; | |
s.push(dot); | |
if (!hasOwnProperty.call(o, dot)) | |
throw new Error('no property ' + s.join(c) + ' found'); | |
o = o[dot]; | |
} | |
return o; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment