Property Getter / Setter Techniques (v12)

Revision 12 of this benchmark created on


Description

Testing various techniques for creating getters / setters in JavaScript.

Preparation HTML

<script>
  var test;
  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 (arguments.length)
          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;
      }
    };
  })();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Getter / setter methods
test = global.obj1.getProp();
ready
get / set syntax
test = global.obj2.prop;
ready
Object.defineProperty
test = global.obj3.prop;
ready
__defineGetter__
test = global.obj4.prop;
ready
Regular property
test = global.obj.prop;
ready
Combined getter / setter method
test = global.obj5.prop();
ready
Generic get/set methods
test = global.obj6.get('prop');
ready

Revisions

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