Scratch Objects and performance.

So Actionscript 3 is fast…. er than actionscript 2. But performance is still a big bottleneck. One well known fact is object creation is slow. Adobe knows this and is addressing it
@see Tamarin Bugzilla

But I was crunching some code tonight and was startled at just how slow it really is.
Take The following function :

/**
* rotates a point by this quaternion.
*/
public function rotatePoint(p : Point3d) : void {
   // copy of origin p
   var _:Point3d = new Point3d();
   _.x=p.x*2, _.y=p.y*2, _.z=p.z*2;

   p.x -= (y*y + z*z)*_.x - (x*y - z*w)*_.y - (x*z + y*w)*_.z;
   p.y += (x*y + z*w)*_.x - (x*x + z*z)*_.y - (x*w - y*z)*_.z;
   p.z += (x*z - y*w)*_.x + (x*w + y*z)*_.y - (x*x + y*y)*_.z;
}

But if we change this apparently math heavy function to use a scratch object instead of creating a new instance of Point3d each call …

/**
* rotates a point by this quaternion.
*/
public function rotatePoint(p : Point3d) : void {
   // '_' is a scratch Point3d private to this instance
   _.x=p.x*2, _.y=p.y*2, _.z=p.z*2;

   p.x -= (y*y + z*z)*_.x - (x*y - z*w)*_.y - (x*z + y*w)*_.z;
   p.y += (x*y + z*w)*_.x - (x*x + z*z)*_.y - (x*w - y*z)*_.z;
   p.z += (x*z - y*w)*_.x + (x*w + y*z)*_.y - (x*x + y*y)*_.z;
}

// scratch Point3d for quick private use.
// maintains no significance
private static const _ : Point3d = new Point3d();

rotatePoint now executes a stunning 5(FIVE!) times faster.

and since we’re talking performance…
Static variables are usually slow
@see Adobe Jira
But since this scratch object is local there is no HT lookup cost. We’re simply creating one scratch Point3d to be used by all instances of the class. Call it a dirty trick, but we have one thread and its fair game.

5 Responses to “Scratch Objects and performance.”

  1. Doug Marttila Says:

    Good trick. Did you test using a private const for each class? Obviously your way creates less objects (good), but, just curious whether avoiding the static makes it even faster.

  2. jlGauthier Says:

    Yup I tested private var and private const both were immeasurably insignifacant vs static const over 5,000,000 calls.

  3. Pages tagged "tamarin" Says:

    […] tagged tamarinOwn a Wordpress blog? Make monetization easier with the WP Affiliate Pro plugin. Scratch Objects and performance. saved by 10 others     iheartanime bookmarked on 02/25/08 | […]

  4. MichaelGraham Says:

    I had got a desire to make my own organization, but I didn’t earn enough of cash to do that. Thank God my close mate said to take the personal loans. Thence I used the sba loan and made real my old dream.

  5. Corbin Says:

    Very informative blog. Thanks for taking the time to share your view with us.

Leave a Reply