Object.defineProperty vs __defineGetter__ vs normal

JavaScript performance comparison

Test case created by Batiste

Info

Test different access method to an object property

Preparation code

<script>
  obj = {
   _x: 0
  }
 
  var acc = 0;
 
  funct = {
   get: function() {
    return this._x
   },
   set: function(value) {
    this._x = value
   }
  }
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Object.defineProperty
Object.defineProperty(obj, "x", {
 get: funct['get'],
 set: funct['set']
})

for (var i = 0; i < 1000; i++) {
 obj.x = i;
 acc += obj.x;
}
pending…
__defineGetter__
obj.__defineGetter__('x', funct['get']);
obj.__defineSetter__('x', funct['set']);

for (var i = 0; i < 1000; i++) {
 obj.x = i;
 acc += obj.x;
}
pending…
Normal
for (var i = 0; i < 1000; i++) {
 obj._x = i;
 acc += obj._x;
}
pending…
Prototype
obj.prototype = {
 get x() {
  return this._x;
 }, set x(value) {
  this_x = value;
 }
}

for (var i = 0; i < 1000; i++) {
 obj.x = i;
 acc += obj.x;
}
pending…
Setter
obj.setX = function(value) {
 this._x = value;
}

for (var i = 0; i < 1000; i++) {
 obj.setX(i);
 acc += obj._x;
}
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. Here’s a list of current revisions for this page:

1 comment

Veli Pehlivanov commented :

Running the test on IE10 in Win8 Developer Preview yields similar results: direct assignment is fastest, followed by the setter function. Object.defineProperty and prototype getters/setters are similar in performance on the third place. Object.defineGetter is not supported.

I also tried to setup a similar test in a Windows 8 Metro-style Javascript Application (WinJS) and these results also point to the same conclusion. Similar to IE10, Object.defineGetter is not supported by the environment.

Add a comment