Native Types

From ActionScriptWiki

Jump to: navigation, search

Since ActionScript offers multiple types it is possible to choose the appropriate type for a specific operation. It is sometimes not easy to decide which one should be choosen for an iteration but basically you have to choose between Number, int and uint.

Contents

[edit] Simple Iteration

First example is a simple iteration over a set of elements. In such an iteration you will usually need only integer value types. Therefore the correct version is using an int.

[edit] Wrong Version

Both i and n are typed Number which is not needed since the iteration works only with integer values.

const list: Vector.<BitmapData>;
const n: Number = list.length;

for( var i: Number = 0.0; i < n; ++i )
	list[ i ].dispose();

[edit] Correct Version

Marking i and n as integer data types significantly improves performance. It is also important to keep in mind that array access is optimized in the Flash Player for integer values.

const list: Vector.<BitmapData>;
const n: int = list.length;

for( var i: int = 0; i < n; ++i )
	list[ i ].dispose();

If you simply want to iterate over a complete list using a for-loop is a bad idea since an even better version is using a while-loop.

const list: Vector.<BitmapData>;
var i: int = list.length;

while( --i > -1 )
	list[ i ].dispose();

[edit] Complex Iteration

Once an iteration includes calculations it is possible that an integer value gets automatically converted to a floating-point value. Such a conversion is usually an expensive task and it might be faster to iterate over the already converted data type.

[edit] Wrong Version

In this example the call Math.sin( i ) automatically converts the int i to a Number. This is much more expensive than directly using the Number type for i.

const n: int = 4096;
for( var i: int = 0; i < n; ++i )
	trace( Math.sin( i ) );

[edit] Correct Version

The call to Math.sin does not have involve the conversion of i any longer. Although ++i and i < n would be faster using integer types, the conversion is so expensive that this version is faster.

const n: Number = 4096.0;
for( var i: Number = 0.0; i < n; ++i )
	trace( Math.sin( i ) );

Sometimes it is useful to have both options when indexing an array and performing calculations.

const n: int = 4096;
const table: Vector.<Number> = new Vector.<Number>( n, true );

var i: int = 0;
var j: Number = 0.0;

for( ; i < n; ++i, ++j )
	table[ i ] = Math.sin( j );
Personal tools