Property Getter / Setter Techniques

JavaScript performance comparison

Revision 8 of this test case created by john

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;
    });
  })();
</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() + 1);
pending…
get / set
global.obj2.prop = global.obj2.prop + 1;
pending…
Object.defineProperty
global.obj3.prop = global.obj3.prop + 1;
pending…
__defineGetter__
global.obj4.prop = global.obj4.prop + 1;
pending…
Property
global.obj.prop = global.obj.prop + 1;
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.

1 Comment

john (revision owner) commented :

I added Revision 8 in response to a conversation on the V8 JS engine message boards:

http://groups.google.com/group/v8-users/browse_thread/thread/60eb31014225759

Function scope reduces the performance delta. This revision is not truly function scope as I had to place the global var outside the anonymous function but at least shows that method performance decreases significantly outside global scope whereas Object.defineProperty remains relatively stagnant.

Rico, from the Chromium group was nice enough to file a bug for v8 as well:

http://www.google.com/url?sa=D&q=http://code.google.com/p/v8/issues/detail%3Fid%3D1693&usg=AFQjCNF0ckdXSh1Zrxsnwj-uR5Cg4DMGdQ