Comparing if statement with ?: operator
The conditional operator ?: is basically faster than the if statement. As to the exception see an article in JActionScripters:
"When to use the ?: conditional operator"
http://blog.jactionscripters.com/2011/02/09/when-to-use-the-conditional-operator/
条件演算子?:は、基本的にはifステートメントより処理は速いようです。そうでない場合については、F-siteの記事をご参照ください。
F-site「条件演算子?:はいつ使うとよいか」
http://f-site.org/articles/2011/02/09113238.html
♥0 |
Line 71 |
Modified 2011-02-11 15:09:39 |
MIT License
archived:2017-03-10 06:12:42
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/noWZ
*/
package {
import flash.display.Sprite;
import flash.utils.getTimer;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
[SWF(width = "240",height = "180")]
public class Test_if_vs_conditional_operator extends Sprite {
private const MAX_NUMBER:uint = 10000000;
private var testData:Vector.<int> = new Vector.<int>(MAX_NUMBER);
private var my_txt:TextField = new TextField();
private var label_txt:TextField = new TextField();
private var my_fmt:TextFormat = new TextFormat();
public function Test_if_vs_conditional_operator() {
// Creating a TextField for display
createTextField();
setData();
warmingUp();
// Starting Test
test_if();
test_conditional_operator();
}
private function warmingUp():void {
var temp:Boolean;
var started:int = getTimer();
for (var i:uint = 0; i < MAX_NUMBER; i++) {
var n:int = testData[i];
temp = true;
}
}
private function test_if():void {
var temp:Boolean;
var started:int = getTimer();
for (var i:uint = 0; i < MAX_NUMBER; i++) {
var n:int = testData[i];
if ((n > 0)) {
temp = true;
} else {
temp = false;
}
}
xTrace("if", getTimer() - started);
}
private function test_conditional_operator():void {
var temp:Boolean;
var started:int = getTimer();
for (var i:uint = 0; i < MAX_NUMBER; i++) {
var n:int = testData[i];
temp = (n > 0) ? true : false;
}
xTrace("?: operator", getTimer() - started);
}
private function setData():void {
for (var i:uint = 0; i < MAX_NUMBER; i++) {
testData[i] = Math.pow(-1,i);
}
}
private function createTextField():void {
addChild(my_txt);
addChild(label_txt);
my_fmt.align = TextFormatAlign.RIGHT;
my_txt.x += 50;
my_txt.defaultTextFormat = my_fmt;
my_txt.autoSize = TextFieldAutoSize.RIGHT;
label_txt.autoSize = TextFieldAutoSize.LEFT;
}
private function xTrace(_str:String,n:int):void {
my_txt.appendText(String(n) + "\n");
label_txt.appendText(_str + ":" + "\n");
}
}
}