Accessing Array elements vs dynamic variables with brackets
Accessing Array elements is quicker than accessing dynamic variables with brackets []. Case of a Vector is added for comparison.
インスタンスを配列に入れて取出す方が、配列アクセス演算子[]で文字列名を指定するより速い。比較のため、Vectorの例も加えた。
/**
* Copyright Fumio ( http://wonderfl.net/user/Fumio )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/m8ok
*/
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;
[SWF(width = "240",height = "180")]
dynamic public class Testing_name_and_Array extends Sprite {
private const AMOUNT:uint = 1000;
private const COUNT:uint = 1000;
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 test_array:Array = [];
private var testVector:Vector.<Sprite> = new Vector.<Sprite>(COUNT);
public function Testing_name_and_Array() {
// Creating a TextField for display
createTextField();
// Starting test
initialize();
testing_getElements();
testing_getVectorElements();
testing_get_names();
}
private function initialize():void {
for (var i:uint = 0; i < COUNT; i++) {
var mySprite:Sprite = new Sprite();
mySprite.name = "instance" + i;
this["instance" + i] = mySprite;
test_array[i] = mySprite;
testVector[i] = mySprite;
}
}
private function testing_getElements():void {
started = getTimer();
for (var i:int = 0; i < AMOUNT; i++) {
getElements();
}
xTrace(getTimer() - started);
}
private function testing_getVectorElements():void {
started = getTimer();
for (var i:int = 0; i < AMOUNT; i++) {
getVectorElements();
}
xTrace(getTimer() - started);
}
private function testing_get_names():void {
started = getTimer();
for (var i:int = 0; i < AMOUNT; i++) {
get_names();
}
xTrace(getTimer() - started);
}
private function getElements():void {
for (var i:uint = 0; i < COUNT; i++) {
var mySprite:Sprite = test_array[i];
}
}
private function getVectorElements():void {
for (var i:uint = 0; i < COUNT; i++) {
var mySprite:Sprite = testVector[i];
}
}
private function get_names():void {
for (var i:uint = 0; i < COUNT; i++) {
var mySprite:Sprite = this["instance" + i];
}
}
private function createTextField():void {
addChild(my_txt);
addChild(label_txt);
my_txt.x += 70;
my_txt.autoSize = TextFieldAutoSize.RIGHT;
my_fmt.align = TextAlign.RIGHT;
my_txt.defaultTextFormat = my_fmt;
label_txt.autoSize = TextFieldAutoSize.LEFT;
label_txt.text = "accessing Array elements:\naccessing Vector elements:\naccessing by name strings:";
}
private function xTrace(n:int):void {
my_txt.appendText(String(n) + "\n");
}
}
}