Comparing access speed to get a property of elements in an Array
Storing each elements into a typed variable seems to be faster than accessing directly to elements' properties.
配列エレメントのオブジェクトから直接プロパティを取出すより、オブジェクトを一旦型指定した変数にとる方が速いようです。
/**
* Copyright Fumio ( http://wonderfl.net/user/Fumio )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/h0KV
*/
package {
import flash.display.Sprite;
import flash.utils.getTimer;
import flash.text.TextField;
[SWF(width = "240",height = "180")]
public class AccessingElements extends Sprite {
private const MAX_NUMBER:uint = 1000000;
private var started:int;
private var my_txt:TextField = new TextField ;
private var label_txt:TextField = new TextField ;
public function AccessingElements() {
// Creating a TextField for display
createTextField();
// Starting Test
useTypedVariable();
directlyAccess();
useVector();
}
private function useTypedVariable():void {
var my_array:Array = getArray();
started = getTimer();
for (var i:uint = 0; i < MAX_NUMBER; i++) {
var myElement:Element = my_array[i];
var temp:int = myElement.property;
}
xTrace(getTimer() - started);
}
private function directlyAccess():void {
var my_array:Array = getArray();
started = getTimer();
for (var i:uint = 0; i < MAX_NUMBER; i++) {
var temp:int = my_array[i].property;
}
xTrace(getTimer() - started);
}
private function useVector():void {
var myVector:Vector.<Element> = getVector();
started = getTimer();
for (var i:uint = 0; i < MAX_NUMBER; i++) {
var myElement:Element = myVector[i];
var temp:int = myElement.property;
}
xTrace(getTimer() - started);
}
private function getArray():Array {
var _array:Array = new Array();
for (var i:uint = 0; i < MAX_NUMBER; i++) {
_array[i] = new Element();
}
return _array;
}
private function getVector():Vector.<Element> {
var myVector:Vector.<Element> = new Vector.<Element>(MAX_NUMBER, true);
for (var i:uint = 0; i < MAX_NUMBER; i++) {
myVector[i] = new Element();
}
return myVector;
}
private function createTextField():void {
addChild(my_txt);
addChild(label_txt);
my_txt.x += 80;
label_txt.text = "Array (typed):\nArray (direct):\nVector:";
}
private function xTrace(n:int):void {
my_txt.appendText(String(n) + "\n");
}
}
}
internal class Element {
internal var property:int = 0;
function Element() {}
}