Functionの速度比較

by wantora
♥0 | Line 64 | Modified 2009-05-22 10:12:36 | MIT License
play

ActionScript3 source code

/**
 * Copyright wantora ( http://wonderfl.net/user/wantora )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/34uc
 */

package {
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	public class Main extends Sprite {
		private var textField:TextField;
		
		public function Main() {
			textField = new TextField();
			textField.autoSize = TextFieldAutoSize.LEFT;
			textField.text = "クリックで開始";
			
			addChild(textField);
			stage.addEventListener(MouseEvent.CLICK, onClick);
		}
		
		private function onClick(e:MouseEvent):void {
			stage.removeEventListener(MouseEvent.CLICK, onClick);
			textField.text = "";
			textField.appendText("通常のメソッド呼び出し: " + test1() + "ms\n");
			textField.appendText("通常のメソッド呼び出し(引数あり): " + test2() + "ms\n");
			textField.appendText("メソッドを一旦変数に入れてから呼び出し: " + test3() + "ms\n");
			textField.appendText("メソッドを一旦変数に入れてから呼び出し(引数あり): " + test4() + "ms\n");
		}
		
		private function test1():int {
			var a:A = new A();
			var t:int = new Date().time;
			for (var i:int = 0; i < 5000000; i++) {
				a.method1();
			}
			return int(new Date().time - t);
		}
		
		private function test2():int {
			var a:A = new A();
			var t:int = new Date().time;
			for (var i:int = 0; i < 5000000; i++) {
				a.method2(1, 2, 3);
			}
			return int(new Date().time - t);
		}
		
		private function test3():int {
			var method1:Function = new A().method1;
			var t:int = new Date().time;
			for (var i:int = 0; i < 5000000; i++) {
				method1();
			}
			return int(new Date().time - t);
		}
		
		private function test4():int {
			var method2:Function = new A().method2;
			var t:int = new Date().time;
			for (var i:int = 0; i < 5000000; i++) {
				method2(1, 2, 3);
			}
			return int(new Date().time - t);
		}
	}
}

class A {
	public function method1():int {
		return 0;
	}
	public function method2(x:int, y:int, z:int):int {
		return 0;
	}
}