Casting

From ActionScriptWiki

Jump to: navigation, search

Casting is important when elements in an Array are accessed directly. The Flash Player has to figure out what kind of element is inside the Array and this step can be skipped.

Contents

[edit] Wrong Version

The element of the Array is accessed directly. This is bad because the Flash Player does not know about the object and code refactoring becomes impossible.

const list: Array /* of Vector3D */;
var i: int = list.length;

while( --i > -1 )
	list[ i ].x = Math.random();

[edit] Correct Version

In this case the elements inside list are casted to Vector3D.

const list: Array /* of Vector3D */;
var i: int = list.length;

while( --i > -1 )
	Vector3D( list[ i ] ).x = Math.random();

In most cases it is possible to use a Vector.<T> object and thus the cast becomes unnecessary.

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

while( --i > -1 )
	list[ i ].x = Math.random();

[edit] Different Casts

There is a very important difference between the Cast(object) and (object as Cast) operation. When using the as operator the Flash Player tests if the object type and the type of the cast match. If they do not match the result is converted to null. In the other version the Flash Player throws an error if both types do not match and does not perform a conversion to null. This version is significantly faster than using the as operator.

[edit] See Also

Personal tools