Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Benchmark of several variants of type casting in AS3
package
{
import flash.display.*;
import flash.text.*;
import flash.utils.*;
public class CastingSpeed extends Sprite
{
public function CastingSpeed()
{
var logger:TextField = new TextField();
logger.autoSize = TextFieldAutoSize.LEFT;
addChild(logger);
function log(msg:*): void { logger.appendText(msg+"\n"); }
const ITERATIONS:int = 5000000;
var i:int;
var beforeTime:int;
var afterTime:int;
var bmd:Object = new BitmapData(1, 1);
var spr:Object = new Sprite();
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
}
afterTime = getTimer();
log("empty loop: " + (afterTime-beforeTime));
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
bmd = bmd;
}
afterTime = getTimer();
log("assignment only: " + (afterTime-beforeTime));
log("Cast succeeds without assignement:");
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
BitmapData(bmd);
}
afterTime = getTimer();
log("\tFunction call style: " + (afterTime-beforeTime));
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
bmd as BitmapData;
}
afterTime = getTimer();
log("\tAs keyword: " + (afterTime-beforeTime));
log("Cast succeeds:");
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
var result : BitmapData = BitmapData(bmd);
}
afterTime = getTimer();
log("\tFunction call style: " + (afterTime-beforeTime));
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
if (bmd is BitmapData)
{
var result : BitmapData = bmd as BitmapData;
}
}
afterTime = getTimer();
log("\tAs keyword with guard: " + (afterTime-beforeTime));
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
var result : BitmapData = bmd as BitmapData;
}
afterTime = getTimer();
log("\tAs keyword without guard: " + (afterTime-beforeTime));
log("Cast fails:");
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
try
{
var result : BitmapData = BitmapData(spr);
}
catch (err:TypeError)
{
}
}
afterTime = getTimer();
log("\tFunction call style: " + (afterTime-beforeTime));
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
if (spr is BitmapData)
{
var result : BitmapData = spr as BitmapData;
}
}
afterTime = getTimer();
log("\tAs keyword with guard: " + (afterTime-beforeTime));
beforeTime = getTimer();
for (i = 0; i < ITERATIONS; ++i)
{
var result : BitmapData = spr as BitmapData;
}
afterTime = getTimer();
log("\tAs keyword without guard: " + (afterTime-beforeTime));
}
}
}
empty loop: 13
assignment only: 148
Cast succeeds without assignement:
Function call style: 155
As keyword: 13
Cast succeeds:
Function call style: 230
As keyword with guard: 258
As keyword without guard: 195
Cast fails:
Function call style: 12884
As keyword with guard: 134
As keyword without guard: 197
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.