forked from: Evaluating key codes with switch statement vs an array
forked from Evaluating key codes with switch statement vs an array (diff: 3)
ActionScript3 source code
/**
* Copyright Fumio ( http://wonderfl.net/user/Fumio )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/gYQO
*/
// forked from Fumio's Evaluating key codes with switch statement vs an array
package {
import flash.display.Sprite;
import flash.utils.getTimer;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flashx.textLayout.formats.TextAlign;
import flash.ui.Keyboard;
[SWF(width = "240",height = "180")]
public class Testing_switch_and_Array extends Sprite {
private const AMOUNT:uint = 1000000;
private var started:uint;
private var my_txt:TextField = new TextField();
private var label_txt:TextField = new TextField();
private var my_fmt:TextFormat = new TextFormat();
private var mySprite:Sprite = new Sprite();
private var operations_array:Array = [];
public function Testing_switch_and_Array() {
// Creating a TextField for display
createTextField();
// Starting test
initialize();
test_switch();
testArray();
}
private function initialize():void {
addChild(mySprite);
operations_array[Keyboard.LEFT] = ["x",-1];
operations_array[Keyboard.RIGHT] = ["x",1];
operations_array[Keyboard.UP] = ["y",-1];
operations_array[Keyboard.DOWN] = ["y",1];
}
private function test_switch():void {
started = getTimer();
for (var i:int = 0; i < AMOUNT; i++) {
use_switch(36 + (i % 5));
}
xTrace(getTimer() - started);
}
private function testArray():void {
started = getTimer();
for (var i:int = 0; i < AMOUNT; i++) {
useArray(36 + (i % 5));
}
xTrace(getTimer() - started);
}
private function use_switch(nKeyCode:uint):void {
switch (nKeyCode) {
case (Keyboard.LEFT) :
mySprite.x -= 1;
break;
case (Keyboard.RIGHT) :
mySprite.x += 1;
break;
case (Keyboard.UP) :
mySprite.y -= 1;
break;
case (Keyboard.DOWN) :
mySprite.y += 1;
break;
}
}
private function useArray(nKeyCode:uint):void {
var operation_array:Array = operations_array[nKeyCode];
if (operation_array) {
var property_str:String = operation_array[0];
var pixels:Number = operation_array[1];
mySprite[property_str] += pixels;
}
}
private function createTextField():void {
addChild(my_txt);
addChild(label_txt);
my_txt.x += 50;
my_txt.autoSize = TextFieldAutoSize.RIGHT;
my_fmt.align = TextAlign.RIGHT;
my_txt.defaultTextFormat = my_fmt;
label_txt.autoSize = TextFieldAutoSize.LEFT;
label_txt.text = "using switch to test codes:\nusing Array to test codes:";
}
private function xTrace(n:int):void {
my_txt.appendText(String(n) + "\n");
}
}
}