Angular $parse test

Benchmark created on


Description

Testing $parse versus a javascript function to extract nested object using a string key. http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
<script>
function ParseCtrl ($scope, $parse) {
var data={
 depth: 1,
 nested: {
  depth: 2,
  nested: {
   depth: 3
  }
 }
};

var parse1 = $parse('depth');
var parse2 = $parse('nested.depth');
var parse3 = $parse('nested.nested.depth');

$scope.parseData = function(i){
   console.log(i, parse1(data));
   console.log(i, parse2(data));
   console.log(i, parse3(data));
}

$scope.refData = function(i){
   console.log(i, ref(data, 'depth'));
   console.log(i, ref(data, 'nested.depth'));
   console.log(i, ref(data, 'nested.nested.depth'));
}

function ref(obj, path, def){
        if (!path) return path;
        for(var i = 0, path = path.split('.'),len = path.length; i < len; i++){
            if(!obj || typeof obj !== 'object') return def;
            obj = obj[path[i]];
        }
        if(obj === undefined) return def;
        return obj;
    }
};
angular.element(document).ready(function() {
    window.ANGAPP = {
      scope: $('#angular').scope()
    };
  });
</script>
    <div style="width: 200px; height: 300px; overflow: hidden" ng-app>
    <span  ng-controller="ParseCtrl" id="angular"></span>
</div>

Test runner

Ready to run.

Testing in
TestOps/sec
Parse
for (var i = 0; i < 1000; i++)
  ANGAPP.scope.parseData(i);
ready
Ref
for (var i = 0; i < 1000; i++)
  ANGAPP.scope.refData(i);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.