Property Getter / Setter Techniques

JavaScript performance comparison

Revision 3 of this test case created by Miller Medeiros

Preparation code

<script>
  var _tmp = 0;
  
  var obj = {
   prop: 0
  }
  
  var obj1 = {
   _prop: 0,
   getProp: function() {
    return this._prop;
   },
   setProp: function(value) {
    this._prop = value;
   }
  };
  
  var obj2 = {
   _prop: 0,
   get prop() {
    return this._prop;
   },
   set prop(value) {
    this._prop = value;
   },
  };
  
  var obj3 = {
   _prop: 0
  }
  
  Object.defineProperty(obj3, "prop", {
   get: function() {
    return this._prop;
  
   },
   set: function(val) {
    this._prop = val;
   }
  });
  
  var obj4 = {
   _prop: 0
  }
  
  obj4.__defineGetter__("prop", function() {
   return this._prop;
  });
  
  obj4.__defineSetter__("prop", function(val) {
   this._prop = val;
  });
</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
Methods
obj1.setProp(obj1.getProp() + 1);
pending…
get / set
obj2.prop = obj2.prop + 1;
pending…
Object.defineProperty
obj3.prop = obj3.prop + 1;
pending…
__defineGetter__
obj4.prop = obj4.prop + 1;
pending…
Property
obj.prop = obj.prop + 1;
pending…
Methods #2
obj1.setProp(_tmp);
_tmp = obj1.getProp() + 1;
pending…
get / set #2
obj2.prop = _tmp;
_tmp = obj2.prop + 1;
pending…
Object.defineProperty #2
obj3.prop = _tmp;
_tmp = obj3.prop + 1;
pending…
__defineGetter__ #2
obj4.prop = _tmp;
_tmp = obj4.prop + 1;
pending…
Property #2
obj.prop = _tmp;
_tmp = obj.prop + 1;
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.

1 Comment

Miller Medeiros (revision owner) commented :

Updated code for __defineGetter__ since it was named _prop and we are accessing prop, also updated obj used on regular property lookup since the property name started with an underscore by mistake. So during loop value was being set to something like "undefined111111" instead of increasing the numeric value (which is twice as fast).

I've added new test cases to check if the JS engines are being smart while setting/getting same property and avoiding lookups but I don't think that the method I used is reliable since it is not too hard to find out that the _tmp value is only being used for setting obj.prop.