Skip to content

Instantly share code, notes, and snippets.

@bahamas10
Last active August 25, 2015 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahamas10/3a6516358d86bcef11c5 to your computer and use it in GitHub Desktop.
Save bahamas10/3a6516358d86bcef11c5 to your computer and use it in GitHub Desktop.
dotted lookup performance
$ ./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
  1. pure js implementation consistently takes 0ms, whereas new Function fluctuates.
  2. manual lookup can also differentiate undefined set on the object, and a property not found
#!/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