Property Getter / Setter Techniques (v19)

Revision 19 of this benchmark created by Andrew Petersen on


Description

Testing various techniques for creating getters / setters in JavaScript.

Testing a variation of 'Combined getter / setter method'. I had heard that using the 'arguments' object requires a heavy performance hit

Preparation HTML

<script>
  var global = this;
  
  (function() {
    global.obj = {
      prop: 0
    };
  
    global.obj1 = {
      _prop: 0,
      getProp: function() {
        return this._prop;
      },
      setProp: function(value) {
        this._prop = value;
      }
    };
  
    global.obj2 = {
      _prop: 0,
      get prop() {
        return this._prop;
      },
      set prop(value) {
        this._prop = value;
      }
    };
  
  
    global.obj3 = {
      _prop: 0
    }
  
  
    Object.defineProperty(global.obj3, "prop", {
      get: function() {
        return this._prop;
  
      },
      set: function(val) {
        this._prop = val;
      }
    });
  
    global.obj4 = {
      _prop: 0
    }
  
  
    global.obj4.__defineGetter__("prop", function() {
      return this._prop;
    });
  
    global.obj4.__defineSetter__("prop", function(val) {
      this._prop = val;
    });
  
    global.obj5 = {
      _prop: 0,
      prop: function(value) {
        if (value !== void 0)
          this._prop = value;
        else
          return this._prop;
      }
    };
  
    global.obj6 = {
      attributes: {
        prop: 0
      },
      get: function(name) {
        return this.attributes[name];
      },
      set: function(name, value) {
        this.attributes[name] = value;
      }
    };

    global.obj7 = {
      _prop: 0,
      get: function(key) {
        return this[key];
      },
      set: function(key, value) {
        this[key] = value;
      }
    };

global.obj8 = {};
  Object.defineProperty(global.obj8, "getProp", {
   value: function() {
    return this._prop;
  
   }
  });
  Object.defineProperty(global.obj8, "setProp", {
   value: function(val) {
    this._prop = val;
   }
  });
  })();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Getter / setter methods
global.obj1.setProp(global.obj1.getProp() + 1);
ready
get / set syntax
global.obj2.prop = global.obj2.prop + 1;
ready
Object.defineProperty
global.obj3.prop = global.obj3.prop + 1;
ready
__defineGetter__
global.obj4.prop = global.obj4.prop + 1;
ready
Regular property
++global.obj.prop;
ready
Combined getter / setter method
global.obj5.prop(global.obj5.prop() + 1);
ready
Generic get/set methods (with key)
global.obj7.set('_prop', global.obj7.get('_prop') + 1);
ready
defineProperty function
var obj8 = global.obj8; obj8.setProp(obj8.getProp() + 1);
ready
attribute
global.obj6.set('prop', global.obj6.get('prop') + 1);
ready

Revisions

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