Catch exception

JavaScript performance comparison

Revision 6 of this test case created by subzey

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function getProperty(obj, prop) {
    return prop.split('.')
      .reduce(function(m, i) {
        return m && typeof m == 'object' ? m[i] : null;
      }, obj);
  }
  
  function getPropertyFast(obj, prop) {
    var parts = prop.split('.');
    for (var i = 0; i < parts.length; i++) {
      if (!obj)
        return null;
      obj = obj[parts[i]];
    }
    return obj;
  }
  
  
  var partsCache = {};
  function getPropertyFast2(obj, prop) {
    if (!partsCache.hasOwnProperty(prop)){
      partsCache[prop] = prop.split('.');
    }
    var parts = partsCache[prop];
    for (var i = 0; i < parts.length; i++) {
      if (!obj)
        return null;
      obj = obj[parts[i]];
    }
    return obj;
  }
  
  function getPropertyCoerce(object, prop){
  	var path = prop.split('.');
  	var root = object;
  	for (var i=0; i<path.length; i++){
  		root = Object(root)[path[i]];
  	}
  	return root;
  }
  
  var obj = {
    a: {
      b: {
        c: 42
      }
    }
  };
  var result;

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Use try/catch block to suppress errors
try {
  result = obj.a.x.y;
} catch (e) {}
pending…
Use function to get property
result = getProperty(obj, 'a.x.y');
pending…
Really fast function
result = getPropertyFast(obj, 'a.x.y');
pending…
less GC usage
result = getPropertyFast2(obj, 'a.x.y');
pending…
Coerce instead of check
result = getPropertyCoerce(obj, 'a.x.y');
pending…

Compare results of other browsers

Revisions

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

0 Comments