In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

Recycling vs Creating objects 2

Setting basic properties to existing objects is much faster than creating new objects. This code uses a Matrix instance and reset it with Matrix.identity() method.

既存のオブジェクトは使い回した方が、新たにつくり直すより速い。Matrixインスタンスを使い、Matrix.identity()メソッドで初期化した。
/**
 * Copyright Fumio ( http://wonderfl.net/user/Fumio )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/8AUe
 */

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;
	import flash.geom.Matrix;
	[SWF(width = "240",height = "180")]
	public class RecyclingObject2 extends Sprite {
		static private const MAX_NUMBER:uint = 100000;
		static private const DEGREES:Number = 360;
		static private const DEGREES_TO_RADIANS:Number = Math.PI / 360;
		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();
		public function RecyclingObject2() {
			// Creating a TextField for display
			// addChild(mySprite);
			createTextField();
			// Starting Test
			create();
			recycle();
		}
		private function create():void {
			var nWidth:uint = stage.stageWidth;
			var started:int = getTimer();
			for (var i:int = 0; i < MAX_NUMBER; i++) {
				var n:Number = i % DEGREES;
				var temp:Matrix = new Matrix();
				temp.rotate(n);
				// trace(temp);  //
			}
			xTrace("create",getTimer() - started);
		}
		private function recycle():void {
			var nMax:int = MAX_NUMBER;
			var nWidth:uint = stage.stageWidth;
			var started:int = getTimer();
			var temp:Matrix = new Matrix  ;
			for (var i:int = 0; i < nMax; i++) {
				var n:Number = i % DEGREES;
				temp.identity();
				temp.rotate(n);
				// trace(temp);  //
			}
			xTrace("recycle",getTimer() - started);
		}
		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");
		}
	}
}