Property Getter / Setter Techniques (v7)

Revision 7 of this benchmark created by Scott Wolchok on


Description

Testing various techniques for creating getters / setters in JavaScript. This revision uses actual prototype-based classes where possible; seems to result in a significant speedup for the method-based version.

Preparation HTML

<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>

Setup

var obj = new BareProperty();
    var obj1 = new GetterAndSetter();
    var obj2 = new GetSet();
    var obj3 = new DefineProperty();
    var obj4 = new DefineGetterSetter();

Test runner

Ready to run.

Testing in
TestOps/sec
Methods
obj1.setProp(obj1.getProp() + 1);
ready
get / set
obj2.prop = obj2.prop + 1;
ready
Object.defineProperty
obj3.prop = obj3.prop + 1;
ready
__defineGetter__
obj4.prop = obj4.prop + 1;
ready
Property
obj.prop = obj.prop + 1;
ready

Revisions

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