Thursday, July 30, 2009

Code Optimization in Actionscript

3D graphics in Flash are usually handled by the CPU almost no assistance of any fancy 3D acceleration GPU. Thus, framerate is a very important concern.

I found a very useful guide on Code Optimization in Actionscript. For exampled, it states:

"Denormal numbers are floating point numbers that are really small. When such a number occurs the CPU switches into denormal mode and calculations become very slow.

Example


In this example the framerate will jump from approximately 40fps to 1fps. The reason are denormal numbers.


private var _denormals: Vector.;

private function init(): void
{
_denormals = new Vector.( 0xfffff, true );

var n: int = 0xfffff;

while( --n > -1 )
_denormals[ n ] = 1e-256;//very small number!

EnterFrameProvider.connect( enterFrame );
}

private function enterFrame(): void
{
var n: int = 0xfffff;

while( --n > -1 )
_denormals[ n ] *= 0.5;//do some calculations with very small numbers
}


ActionScript Solution

There are a couple of solutions to deal with denormal numbers. Some try to avoid them by adding always a very small value or by adding some white noise. In ActionScript the best and most simple solution is by adding and subtracting an anti-denormal constant.
[edit] Solution

Example

This solution is easy to implement in ActionScript and will result in real zero values.


_denormals[ n ] = _denormals[ n ] * 0.5 + 1e-18 - 1e-18;//avoiding denormals


This is the same example with the fix for denormal numbers. The framerate will now stay at approximately 40fps."

No comments:

Post a Comment