Tag Archive for 'Type conversion'

as Class vs. Class(..)

Some of you might think that

p as Point

and

Point( p )

are equal. They might “mean” the same but they are not. First of all if p can’t be converted to Point result of the first operation is null, but the second one will fail with an error like this:

TypeError: Error #1034: Type Coercion failed: cannot convert 42 to flash.geom.Point.

What’s more, the first one is faster. Here’s the test:

public function typetest()
{
  var total: int;
  for ( var i: int = 0; i < 10; i++ )
    total += execute();
  trace( "as", total/10 );

  total = 0;
  for ( var i: int = 0; i < 10; i++ )
    total += execute2();
  trace( "cast", total/10 );
}

private function execute(): int
{
  var t: int = getTimer();
  var i: int = 0;
  var p: * = new Point();

  for ( i; i < 1000000; i++ )
  {
    p as Point;
  }
  return getTimer() - t;
}

private function execute2(): int
{
  var t: int = getTimer();
  var i: int = 0;
  var p: * = new Point();

  for ( i; i < 1000000; i++ )
  {
    Point(p);
  }
  return getTimer() - t;
}

This code outputs for me the following execution times:

as 157
cast 217.7