deep property access benchmarks

testing out various methods of accessing deep properties in JavaScript. NOTE: Need to open the JS console to see the results

by sym3tri

HTML

Run with JavaScript console open to view the results

JavaScript

// recursive approach
function spropRecursive(obj, ns) {

    function recurse(o, props) {
        if (props.length === 0) {
            return o;
        }
        if (!o) {
            return;
        }
        return recurse(o[props.shift()], props);
    }

    return recurse(obj, ns.split('.'));
}

// iterative approach
function spropItr(obj, ns) {
    var result,
        i,
        props,
        len;

    if (!obj) {
        return;
    }
    
    result = obj
    i = 0;
    props = ns.split('.');
    len = props.length
    
    for(; i<len; i++) {
        result = result[props[i]];
    }
    
    return result;
}

// iterative approach without calling string.split, instead pass an ordered array of strings
// string.split() seems to be expensive, so this is a huge optimization
function spropItrNoSplit(obj, props) {
    var result,
        i,
        len;

    if (!obj) {
        return;
    }
    
    result = obj
    i = 0;
    len = props.length
    
    for(; i<len; i++) {
        result = result[props[i]];
    }
    
    return result;
}

// control case for direct access to the property
function direct(obj) {
    var result = undefined;
    result = obj.foo.bar.bang.bing.oof;
    return result;
}

// this is what you'd normally do without a helper function
function multipleIfs(obj) {

    if(obj.foo && obj.foo.bar && obj.foo.bar.bang && obj.foo.bar.bang.bing) {
        return obj.foo.bar.bang.bing.oof;
    }
}

// test with a try catch, always failing
function trycatchFail(obj) {
    var result = undefined;
    
    try {
        // doesnt exist
        result = obj.a.b.c;
    }
    catch (err) {
    }

    return result;
}

// test with a try catch, always passing
function trycatchPass(obj) {
    var result = undefined;
    
    try {
        result = obj.foo.bar.bang.bing.oof;
    }
    catch (err) {
    }

    return result;
}

function finalChoice(obj, props) {

    var result, i, len;

    if (!obj) {
        return;
    }

    result = obj;
    i...