Flash as3 常用小技巧

关注:1307发表于:2013/5/29

1:String转换成Boolean

1 var s:String="true"; 2 var b:Boolean = (s=="true");

2:清除所有子对象
1 while(container.numChildren > 0) 2 { 3 container.removeChildAt(0); 4 }

3:对于不需要 鼠标交互的对象 设置属性 mouseChildren , mouseEnabled。

4: 尽可能使用 Vector 类而不是 Array 类,Vector 类的读写访问速度比 Array 类快。

5:通过为矢量分配特定长度并将其长度设为固定值,可进一步优化。

 

1 // Specify a fixed length and initialize its length 2 var coordinates:Vector.<Number> = new Vector.<Number>(300000, true); 3 var started:Number = getTimer(); 4 for (var i:int = 0; i< 300000; i++) 5 { 6 coordinates[i] = Math.random()*1024; 7 } 8 trace(getTimer() - started); 9 // output: 48

6:将重用的值存储在常量,可对上面实例进一步优化。

 

 1 // Store the reused value to maintain code easily  2 const MAX_NUM:int = 300000;  3 var coordinates:Vector.<Number> = new Vector.<Number>(MAX_NUM, true);  4 var started:Number = getTimer();  5 for (var i:int = 0; i< MAX_NUM; i++)  6 {  7 coordinates[i] = Math.random()*1024;  8 }  9 trace(getTimer() - started); 10 // output: 47

7:使用BitmapData的 lock() 和 unlock() 方法加快运行速度。

8:对于 TextField 对象,请使用 appendText() 方法,而不要使用 += 运算符。

9: 使用中括号运算符可能会降低性能。将您的引用存储在本地变量中可避免使用该运算符。以下代码示例演示了使用中括号运算
符的效率很低:

 

 1 var lng:int = 5000;  2 var arraySprite:Vector.<Sprite> = new Vector.<Sprite>(lng, true);  3 var i:int;  4 for ( i = 0; i< lng; i++ )  5 {  6 arraySprite[i] = new Sprite();  7 }  8 var started:Number = getTimer();  9 for ( i = 0; i< lng; i++ ) 10 { 11 arraySprite[i].x = Math.random()*stage.stageWidth; 12 arraySprite[i].y = Math.random()*stage.stageHeight; 13 arraySprite[i].alpha = Math.random(); 14 arraySprite[i].rotation = Math.random()*360; 15 } 16 trace( getTimer() - started ); 17 // output : 16

以下优化的版本减少了对中括号运算符的使用:

 1 var lng:int = 5000;  2 var arraySprite:Vector.<Sprite> = new Vector.<Sprite>(lng, true);  3 var i:int;  4 for ( i = 0; i< lng; i++ )  5 {  6 arraySprite[i] = new Sprite();  7 }  8 var started:Number = getTimer();  9 var currentSprite:Sprite; 10 for ( i = 0; i< lng; i++ ) 11 { 12 currentSprite = arraySprite[i]; 13 currentSprite.x = Math.random()*stage.stageWidth; 14 currentSprite.y = Math.random()*stage.stageHeight; 15 currentSprite.alpha = Math.random(); 16 currentSprite.rotation = Math.random()*360; 17 } 18 trace( getTimer() - started ); 19 // output : 9

10: 尽可能使用内联代码以减少代码中函数的调用次数。例如:

1 currentValue > 0 ? currentValue : -currentValue;

 

比下面这种快

 

1 Math.abs ( currentValue );   

 

11:避免计算循环中的语句。

不计算循环中的语句也可实现优化。以下代码遍历数组,但未进行优化,因为在每次遍历时都需要计算数组长度:

 

1 for (var i:int = 0; i< myArray.length; i++) 2 { 3 }

最好存储该值并重复使用:
1 var lng:int = myArray.length; 2 for (var i:int = 0; i< lng; i++) 3 { 4 }

12:对 while 循环使用相反的顺序。

 

以相反顺序进行 while 循环的速度比正向循环快:

 

1 var i:int = myArray.length; 2 while (--i > -1) 3 { 4 }

13:通常,使用尽可能低的帧速率可以提高性能。

在线咨询

点击开始 QQ咨询
TOP
{"error":401,"message":"site error"}