Since we are planing to release a detailed paper about AS3 optimizations and techniques I was thinking about another optimization for one of the daily problems. Looping through an array that contains objects. The fastest code to do this is
[as]for (;i
{
v0 = array[i];
l = v0.length;
}[/as]
v0 is a local variable for my custom class which looks like this
[as]class Vector3D
{
public var x: Number;
public var y: Number;
public var z: Number;
public function Vector3D( x: Number, y: Number, z: Number )
{
this.x = x;
this.y = y;
this.z = z;
}
public function get length(): Number
{
return Math.sqrt( x * x + y * y + z * z );
}
}[/as]
Looks like from a real scenario. You can replace the vector class also with a particle class or whatever. It does not matter. The point is this loop takes 272ms for 1000000 iterations. It is pretty good already but if you add one more parameter to the Vector3D class you can get even faster. This is my modified Vector3D called LVector3D
[as]class LVector3D
{
public var x: Number;
public var y: Number;
public var z: Number;
public var next: LVector3D;
public function LVector3D( x: Number, y: Number, z: Number )
{
this.x = x;
this.y = y;
this.z = z;
}
public function get length(): Number
{
return Math.sqrt( x * x + y * y + z * z );
}
}[/as]
There is a public variable now called next. This variable will always point to the next LVector3D object. The exact same loop takes about 260ms.
[as]var v0: LVector3D = start;
for (;i
{
l = v0.length;
v0 = v0.next;
}[/as]
You see how nice this looks? No ugly [] etc. Our variable is directly typed. And we can speed it up even more! If we replace the for(...) part with while( v0 ) it goes down to 249ms. What is also nice about a linked list is that you could add an easy splice functionality or functions to remove elemts from a list. You just have to change the next reference. If you also add a prev variable it becomes even more easy and you could loop backwards.
Building that list of vectors is also very easy. And it looks beautiful. Compare this
[as]for ( var i: int = 0; i < n; ++i )
array[ i ] = new Vector3D( i, i, i );
var v3d: LVector3D = start;
for ( var j: int = 1; j < n; j++ )
v3d = v3d.next = new LVector3D( j, j, j );[/as]
The start variable is defined in the class as private const vector3d: LVector3D = new LVector3D( 0, 0, 0 );. Very nice. Of course not useful in every case but sometimes if you have to squeeze out what is possible here is another method. So stay tuned for our paper.
Share This