I wrote JS equivalent of my test case in 4 ways.
function mgpoint1(x,y)
{
this.x = x;
this.y = y;
this.getX = function()
{
return this.x;
}
this.getY = function()
{
return this.y;
}
this.getDimension = function()
{
return 2;
}
this.setCoordinates = function(x,y)
{
this.x = x;
this.y = y;
}
}
mgpoint2 is array version of mgpoint1.
mgpoint3 is prototype version of mgpoin1.
mgpoint4 is prototype version of mgpoint2.
function mgpoint3(x,y)
{
this.x = x;
this.y = y;
}
mgpoint3.prototype.getX = function()
{
return this.x;
}
mgpoint3.prototype.getY = function()
{
return this.y;
}
mgpoint3.prototype.getDimension = function()
{
return 2;
}
mgpoint3.prototype.setCoordinates = function(x,y)
{
this.x = x;
this.y = y;
}
The test code is
var i;
var z = 0;
for(i=0; i < 1000000; ++i )
{
var point = new mgpoint1(26,45);
var x = point.getX();
var y = point.getY();
var dimension = point.getDimension();
z = x + y + dimension;
}
Then I wrote another case for simple optimization in js.
function mgpoint5()
{
this.x = 26;
this.y = 45;
}
var i, x, y, point;
var z = 0;
for(i=0; i < 1000000; ++i )
{
point = new mgpoint5();
x = point.x;
y = point.y;
z = x + y + 2;
}
My results are a bit strange.
1 million times
(Chrome 14 results)
JS X-Y: mgpoint1 : 1021
JS Array: mgpoint2 : 1061
Proto X-Y: mgpoint3 : 310
Proto Array: mgpoint4 : 356
Optimized X-Y: mgpoint5 : 308
GWT X-Y: MGPoint2 : 31
GWT Array: MGPoint : 2327
1 million times
(Firefox 5 results)
JS X-Y: mgpoint1 : 1499
JS Array: mgpoint2 : 1732
Proto X-Y: mgpoint3 : 1166
Proto Array: mgpoint4 : 1379
Optimized X-Y: mgpoint5: 455
GWT X-Y: MGPoint2 : 342
GWT Array: MGPoint : 5613