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

ByteArray使い回し

意外とByteArrayって、関数内でだけ使って後はもう破棄したいって場面多いですよね。
そんな時はこんな使い回し方をすると10倍以上高速になるような。
Get Adobe Flash player
by yasurageruheya 29 Jan 2015
/**
 * Copyright yasurageruheya ( http://wonderfl.net/user/yasurageruheya )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/fel8
 */

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	public class FlashTest extends Sprite {
		
		private var time1:Number = 0;
		private var time2:Number = 0;
		
		private const text:TextField = new TextField();
		
		private var testCount:int = 1;
		
		private const LOOP:int = 5000;
		
		public function FlashTest() {
			// write as3 code here..
			text.width = 500;
			addChild(text);
			addEventListener(Event.ENTER_FRAME, test);
		}
		
		private function test(e:Event):void 
		{
			var i:int = LOOP;
			var bytes:ByteArray;
			var timer:int = getTimer();
			while (i--)
			{
				bytes = new ByteArray();
				bytes.writeUnsignedInt(100);
			}
			time1 += getTimer() - timer;
			bytes.position = 0;
			text.text = "new : bytes.bytesAvailable : " + bytes.bytesAvailable + "\n";
			
			bytes = ByteArrayCreator.get();
			//▼ここで大量にバイナリを挿入しても
			bytes.writeMultiByte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "utf-8");
			timer = getTimer();
			i = LOOP;
			while (i--)
			{
				//▼再度受け取る時には中身が初期化されているので
				bytes = ByteArrayCreator.get();
				bytes.writeUnsignedInt(100);
			}
			time2 += getTimer() - timer;
			bytes.position = 0;
			//▼bytes.writeUnsignedInt(100)は一回しか行われていない事になっています。
			text.appendText("get : bytes.bytesAvailable : " + bytes.bytesAvailable + "\n");
			
			text.appendText("new : " + (time1 / testCount) + " ms.\n" +
							"get : " + (time2 / testCount) + " ms.");
			testCount++;
		}
	}
}
import flash.utils.ByteArray;

class ByteArrayCreator
{
	private static const _byteArray:ByteArray = new ByteArray();
	public static function get():ByteArray
	{
		_byteArray.length = 0;
		return _byteArray;
	}
}