Property Getter / Setter Techniques (v92)

Revision 92 of this benchmark created on


Description

Testing various techniques for creating getters / setters in JavaScript.

Preparation HTML

<script>
  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;
  });

var obj5 = {
   _prop: 0
}

function createGetter(key) {
    return function() {
        return this[key];
    };
}

function createSetter(key) {
    return function(val) {
        this[key] = val;
    };
}

function addProperties(obj, properties) {
  for (var i = 0; i < properties.length; i++) {
    var p = properties[i];
    var key = '_' + p;
    Object.defineProperty(obj, p, {
      get: createGetter(key),
      set: createSetter(key)
    });
  }
}

addProperties(obj5, ['prop']);

</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Methods
obj1.setProp((0.5+Math.random())*obj1.getProp());
ready
get / set
obj2.prop = ((0.5+Math.random())*obj2.prop);
ready
Object.defineProperty
obj3.prop = ((0.5+Math.random())*obj3.prop);
ready
__defineGetter__
obj4.prop = ((0.5+Math.random())*obj4.prop);
ready
Property
obj.prop = ((0.5+Math.random())*obj.prop);
ready
Object.defineProperty this[key]
obj5.prop = ((0.5+Math.random())*obj5.prop);
ready

Revisions

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