Property Getter / Setter Techniques (v27)

Revision 27 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,
   prop: function(value) {
    if(value) {
     this._prop = value;
    } else {
     return this._prop;
    }
   }
  };

  var obj6 = {
   prop: 0,
   get: function(key) {
     return this[key];
   },
   set: function(key, val) {
     this[key] = val;
   }
  };

  function get(obj, prop) {
    return obj[prop];
  }
  function set(obj, prop, val) {
    obj[prop] = val;
  }
</script>

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
Global get / set
set(obj, '_prop', get(obj, '_prop') + 1);
ready
Global set (direct get)
set(obj, '_prop', obj._prop + 1);
ready
with hasOwnProperty check
if (obj.hasOwnProperty('_prop')) {
  obj._prop = obj._prop + 1;
}
ready
single function
obj5.prop(obj5.prop() + 1);
ready
obj get/set
obj6.set('prop', obj6.get('prop') + 1)
ready

Revisions

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