Property Getter / Setter Techniques

JavaScript performance comparison

Revision 75 of this test case created by Jon-Carlos Rivera

Preparation code

<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;
    });
  })();
var numberArray = [3, 4, 2, 1, 6, 0, 7, 8, 5];
var idx = 0;
var longLivedArray = [];
// Try to optimize this, you dirty engine!
setTimeout(console.log.bind(console), 100000000, longLivedArray);
</script>
      
<script>
Benchmark.prototype.setup = function() {
  global.obj = {
  prop: 0
  };

};

Benchmark.prototype.teardown = function() {
  longLivedArray.unshift(global.obj1.getProp(), global.obj2.prop,  global.obj3.prop, global.obj4.prop, global.obj.prop);
  
  // Limit data usage
  longLivedArray.length = 32;

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Methods
global.obj1.setProp(global.obj1.getProp() + numberArray[numberArray[++idx % 9] % 9]);
pending…
get / set
global.obj2.prop = global.obj2.prop + numberArray[numberArray[++idx % 9] % 9];
pending…
Object.defineProperty
global.obj3.prop = global.obj3.prop + numberArray[numberArray[++idx % 9] % 9];
pending…
__defineGetter__
global.obj4.prop = global.obj4.prop + numberArray[numberArray[++idx % 9] % 9];
pending…
Property
global.obj.prop = global.obj.prop + numberArray[numberArray[++idx % 9] % 9];
pending…

Compare results of other browsers

Revisions

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

0 Comments