I was busy comparing my custom Vector3D class with the flash.geom.Vector3D one when I noticed something. While my classes seemed to perform almost as well as the flash version there was one method where my implementation was much much slower.
This was the cross product method. The only thing different in this method was that it returns a new instance of the Vector3D class. So how was flash able to instantiate its own class much faster than I could?
How they did it I don’t know, but I did some tests and it would seem that setting variable values in the constructor is slow when you do it in your own classes. i.e.
var point3D:Point3D = new Point3D(x,y,z); |
var point3D:Point3D = new Point3D(x,y,z);
Funnily enough the above is a slower in my tests than:
var point3D:Point3D = new Point3D().init(x,y,z); |
var point3D:Point3D = new Point3D().init(x,y,z);
The init function is simply a direct replacement of what was in the constructor:
public function init(x:Number, y:Number, z:Number):Point3D
{
this.x = x;
this.y = y;
this.z = z;
return this;
} |
public function init(x:Number, y:Number, z:Number):Point3D
{
this.x = x;
this.y = y;
this.z = z;
return this;
}
Note that the init method returns the instance too and a speed up is only gained if the constructor is empty.
I think speed up is only noticed in the release version of the player.
Click the button below to try it out: (Point3DX is the one using init)
[swfobj src=”http://blog.bwhiting.co.uk/wp-content/uploads/2010/10/CreationTest1.swf” height=”400″ width=”400″]
I find the init method to be anywhere up to 2 times faster averaging 1.5 times speedup.
Its more marked on larger numbers but I don’t want to explode anyone’s machine now do I.
Also note that it’s a teeeny bit faster again (in some circumstances) if you set the properties directly on the object once it is created as a 3rd alternative but its not always possible (private attributes) and its more lines of code 🙁