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

for,for in,for each,forEach速度比較

package
{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.geom.Point;
	import flash.utils.getTimer;
	
	public class test extends Sprite
	{
		private var array:Array = new Array();
		private var vector:Vector.<Point> = new Vector.<Point>();
		
		public function test()
		{
			var text_field:TextField = new TextField();
			text_field.width = stage.stageWidth;
			text_field.height = stage.stageHeight;
			stage.addChild(text_field);
			
			for(var i:int = 0; i < 250000; i++)
			{
				array.push(new Point());
				vector.push(new Point());
			}

			var _str:String = new String();
			_str += "Array for:" + benchMarkj(a1) + "\r";
			_str += "Array for in:" + benchMarkj(a2) + "\r";
			_str += "Array for each:" + benchMarkj(a3) + "\r";
			_str += "Array forEach1:" + benchMarkj(a4) + "\r";
			_str += "Array forEach2:" + benchMarkj(a5) + "\r";
			_str += array[0].x + "\r";
			_str += "Vector for:" + benchMarkj(v1) + "\r";
			_str += "Vector for in:" + benchMarkj(v2) + "\r";
			_str += "Vector for each:" + benchMarkj(v3) + "\r";
			_str += "Vector forEach1:" + benchMarkj(v4) + "\r";
			_str += "Vector forEach2:" + benchMarkj(v5) + "\r";
			_str += vector[0].x + "\r";
			
			text_field.text = _str;
		}
		
		private function benchMarkj(_fn:Function):int
		{
			var time:int = getTimer();
			_fn();
			return getTimer() - time;
		}
		
		private function a1():void
		{
			for(var i:int = 0; i < array.length; i++) {
				array[i].x++;
			}
		}
		
		private function a2():void
		{
			for(var i:String in array) {
				array[i].x++;
			}
		}
		
		private function a3():void
		{
			for each(var pos:Point in array) {
				pos.x++;
			}
		}
		
		private function a4():void
		{
			array.forEach(function(pos:Point, i:int, array:Array):void
			{
				pos.x++;
			});
		}
		
		private function a5():void
		{
			array.forEach(function(pos:Point, i:int, array:Array):void
			{
				array[i].x++;
			});
		}
		
		private function v1():void
		{
			for(var i:int = 0; i < vector.length; i++) {
				vector[i].x++;
			}
		}
		
		private function v2():void
		{
			for(var i:String in vector) {
				vector[i].x++;
			}
		}
		
		private function v3():void
		{
			for each(var pos:Point in vector) {
				pos.x++;
			}
		}
		
		private function v4():void
		{
			vector.forEach(function(pos:Point, i:int, vector:Vector.<Point>):void
			{
				pos.x++;
			});
		}
		
		private function v5():void
		{
			vector.forEach(function(pos:Point, i:int, vector:Vector.<Point>):void
			{
				vector[i].x++;
			});
		}
	}
}