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

Setting basic properties to existing objects is much faster than creating new objects.  This code uses a Rectangle instance and sets its four properties to it.

既存のオブジェクトは使い回した方が、新たにつくり直すより速い。Rectangleインスタンスに4つの基本プロパティを設定する例で試した。
Get Adobe Flash player
by Fumio 08 Nov 2011
/**
 * Copyright Fumio ( http://wonderfl.net/user/Fumio )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/kTst
 */

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.Rectangle;
	[SWF(width = "240",height = "180")]
	public class RecyclingObject extends Sprite {
		static private const MAX_NUMBER:uint = 1000000;
		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 RecyclingObject() {
			// Creating a TextField for display
			createTextField();
			// Starting Test
			create();
			recycle();
		}
		private function create():void {
			var nMax:int = MAX_NUMBER;
			var nWidth:uint = stage.stageWidth;
			var started:int = getTimer();
			for (var i:int = 0; i < nMax; i++) {
				var n:uint = i % nWidth;
				var temp:Rectangle = new Rectangle(n, n, n, n);
			}
			xTrace("create",getTimer() - started);
		}
		private function recycle():void {
			var nMax:int = MAX_NUMBER;
			var nWidth:uint = stage.stageWidth;
			var started:int = getTimer();
			var temp:Rectangle = new Rectangle  ;
			for (var i:int = 0; i < nMax; i++) {
				var n:uint = i % nWidth;
				temp.x = n;
				temp.y = n;
				temp.width = n;
				temp.height = n;
			}
			xTrace("recycle",getTimer() - started);
		}
		private function createTextField():void {
			addChild(my_txt);
			addChild(label_txt);
			my_fmt.align = TextFormatAlign.RIGHT;
			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");
		}
	}
}