Javascript - Getter are evil? - Some performance tests

According to this nice article Javaworld (09-2003)  I decided to check getters and setters runtime behavior with JavaScript inside different browsers and on different machines. I tested also the different initialization possibilities, with some unexpected, but not really surprising, results.

Some interpretation tries... Chrome seems to be very constant in each kind of implementation, also it slightly improve its performance in newer versions. Firefox has the highest variation, but again newer version have better times. IE9 does a good job in this case, constant times and very fast. As expected IE8 has runtime problems even with this simple script.

It would be nice if some people add their results, maybe with some more browser versions, like Safari, IE10, Opera, ...

The script

var obj = { 
  id: 5, 
  content: '1234567Test'
};
  
var obj2 = new function(){      
  var id = 5;
  var content = '7654321Test';
 
  this.getId = function(){
    return id;
  }
 
  this.getContent = function(){
    return content;
  }
};

var objtmp = function(){        
  var id = 5;
  var content = '7654321Test';

  this.getId = function(){
    return id;
  }
 
  this.getContent = function(){
    return content;
  }
};
var obj3 = new objtmp();

var timeStart = new Date().getTime();   
for (var i = 0; i <= 100000; i++) { 
  document.writeln(i + " " + obj.id + " " + obj.content);
}
alert("Duration " + (new Date().getTime() - timeStart) + " ms");

timeStart = new Date().getTime();
for (var i = 0; i <= 100000; i++) {
  document.writeln(i + " " + obj2.getId() + " " + obj2.getContent());
}
alert("Duration " + (new Date().getTime() - timeStart) + " ms");

timeStart = new Date().getTime();
for (var i = 0; i <= 100000; i++) {
  document.writeln(i + " " + obj3.getId() + " " + obj3.getContent());
}       
alert("Duration " + (new Date().getTime() - timeStart) + " ms");

The results

Win7 SP1 64 Bit  Core i7@3,46GHz (16 GB RAM)


FF (V 23.0)

  1. 193 ms
  2. 6973 ms
  3. 13497 ms

FF (V 20.0)

  1. 139 ms
  2. 13364 ms
  3. 26508 ms

Chrome (28.0.1500.95 m)

  1. 2580 ms
  2. 2698 ms
  3. 2696 ms

Chrome (26.0.1410.43 m)

  1. 2679 ms
  2. 2706 ms
  3. 2743 ms

IE9 (9.0.8112.16421)

  1. 1600 ms
  2. 1632 ms
  3. 1732 ms

WinXP SP3 32 Bit Core2Duo@2,13 GHz (3,24 GB RAM)

FF (V 20.0)

  1. 362 ms
  2. n/a
  3. 89761ms

Chrome (26.0.1410.43 m)

  1. 6200 ms
  2. 6247 ms
  3. 6300 ms

IE8 (8.0.6001.1872)

  1. 8891 ms (with runtime exception)
  2. 9141 ms (with runtime exception)
  3. 76 ms

No comments:

Post a Comment