Javascript prototype operator performance, saves memory, but is it faster?

Benchmark created by Marco Demaio on


Description

Performance difference between calling method that was declared into a Javscript object, and calling the same method that was declared outside of the object with protoype keyword

Code from: http://stackoverflow.com/questions/3493252/javascript-prototype-operator-performance-saves-memory-but-is-it-faster/3493725#3493725

Written by: http://stackoverflow.com/users/279608/andrew

Preparation HTML

<script>
  var X, Y, x, y, i, intNow;
  
  X = function() {};
  X.prototype.message = function(s) {
   var mymessage = s + "";
  }
  X.prototype.addition = function(i, j) {
   return (i * 2 + j * 2) / 2;
  }
  
  Y = function() {
   this.message = function(s) {
    var mymessage = s + "";
   }
   this.addition = function(i, j) {
    return (i * 2 + j * 2) / 2;
   }
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Y method is declared into the Javscript object class
for (i = 0; i < 1000000; i++) {
 y = new Y();
 y.message('hi');
 y.addition(i, 2)
}
ready
X method is declared outside class by using protoype keyword
for (i = 0; i < 1000000; i++) {
 x = new X();
 x.message('hi');
 x.addition(i, 2)
}
ready

Revisions

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