Property Getter / Setter Techniques

JavaScript performance comparison

Revision 7 of this test case created by Scott Wolchok

Preparation code

<script>
  function BareProperty() {
    this.prop = 0;
  }
  
  function GetterAndSetter() {
    this._prop = 0;
  }
  
  GetterAndSetter.prototype.getProp = function() {
    return this._prop;
  };
  
  GetterAndSetter.prototype.setProp = function(value) {
    this._prop = value;
  };
  
  function GetSet() {
    this._prop = 0;
  }
  GetSet.prototype = {
    get prop() {
      return this._prop;
    }, set prop(value) {
      this._prop = value;
    },
  };
  
  function DefineProperty() {
    this._prop = 0;
    Object.defineProperty(this, "prop", {
      get: function() {
        return this._prop;
      },
      set: function(val) {
        this._prop = val;
      }
    });
  }
  
  function DefineGetterSetter() {
    this._prop = 0;
    this.__defineGetter__("prop", function() {
      return this._prop;
    });
  
    this.__defineSetter__("prop", function(val) {
      this._prop = val;
    });
  }
</script>
      
<script>
Benchmark.prototype.setup = function() {
  var obj = new BareProperty();
  var obj1 = new GetterAndSetter();
  var obj2 = new GetSet();
  var obj3 = new DefineProperty();
  var obj4 = new DefineGetterSetter();

};
</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
get / set
obj2.prop = obj2.prop + 1;
pending…
Object.defineProperty
obj3.prop = obj3.prop + 1;
pending…
Methods
obj1.setProp(obj1.getProp() + 1);
pending…
__defineGetter__
obj4.prop = obj4.prop + 1;
pending…
Property
obj.prop = 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.

0 Comments