Javascript prototype versus closure execution speed

When Javascript execution speed matters consider using prototype instead of closures where possible. Even for a small closure the difference can be noticable when called hundreds of times. Consider the following example that implements a Pixel object with some ancillary functions in both the closure and prototype patterns:

// Closure implementation

function Pixel(x, y)

{

  this.x = x;

  this.y = y;

  this.getX = function()

  {

    return this.x;

  }

  this.getY = function()

  {

    return this.y;

  }

  this.setX = function(value)

  {

    this.x = value;

  }

  this.setY = function(value)

  {

    this.y = value;

  }

}

 

// Prototype implementation

function PixelP(x, y)

{

  this.x = x;

  this.y = y;

}

PixelP.prototype.getX = function()

{

  return this.x;

}

PixelP.prototype.getY = function()

{

  return this.y;

}

PixelP.prototype.setX = function(value)

{

  this.x = value;

}

PixelP.prototype.setY = function(value)

{

  this.y = value;

}

 

 

function TestPerformance()

{

  var closureStartDateTime = new Date();

  for (var i = 0; i < 20000; i++)

  {

    var x = new Pixel(i, i);   

  }

  var closureEndDateTime = new Date();

 

  var prototypeStartDateTime = new Date();

  for (var i = 0; i < 20000; i++)

  {

    var x = new PixelP(i, i);   

  }

  var prototypeEndDateTime = new Date();

  var closureTime = closureEndDateTime.getTime() - closureStartDateTime.getTime();

  var prototypeTime = prototypeEndDateTime.getTime() - prototypeStartDateTime.getTime();

  alert("Closure time: " + closureTime + ", prototype time: " + prototypeTime);

}

 

When this is run in IE7 on my machine, the closure implementation takes around 450ms and prototype takes around 140ms. Add two more empty functions and the closure time increases to 560ms and prototype to 155ms.

On Firefox 1.5.0.9 the difference is in the listed example is even larger with the closure taking 515ms and prototype still around 140ms.

For small applications that don't construct hundreds or thousands of the same type of object the execution speed difference between closure and prototype probably doesn't matter so as with all performance advice measure, measure, measure.