Evaluating key codes with switch vs if statements
forked from Evaluating key codes with switch statement vs an array (diff: 19)
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/279p
*/
// 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 = 5000000;
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();
test_if();
}
private function initialize():void {
addChild(mySprite);
}
private function test_switch():void {
started = getTimer();
for (var i:int = 0; i < AMOUNT; i++) {
use_switch(i % 45);
}
xTrace(getTimer() - started);
}
private function test_if():void {
started = getTimer();
for (var i:int = 0; i < AMOUNT; i++) {
use_if(i % 45);
}
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 use_if(nKeyCode:uint):void {
if (nKeyCode == Keyboard.LEFT) {
mySprite.x -= 1;
} else if (nKeyCode == Keyboard.RIGHT) {
mySprite.x += 1;
} else if (nKeyCode == Keyboard.UP) {
mySprite.y -= 1;
} else if (nKeyCode == Keyboard.DOWN) {
mySprite.y += 1;
}
}
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 if to test codes:";
}
private function xTrace(n:int):void {
my_txt.appendText(String(n) + "\n");
}
}
}