编写高效率的AS3代码的小技巧
下面是我的一些测试结果
Array & Object constructing
构造数组和对象的时候,new Array() and new Object()要比 [] and {}慢3倍的时间
Index Number type for Arrays
数组的数字索引类型
ist[int(0)] 比list[0]要快
Create Array vs. Updating Array
再循环语句中避免多次创建数组,最好创建一次用多次更新内容替换
Nulling Array vs. Splicing Array
对于庞大的数组而言就行splice操作是比较耗成本的,要尽量避免
When working with large Arrays splicing is obviously an expensive operation, you can avoid this by nulling the index and skipping it in a null scenario. If you need to splice in order to keep the Array length low. Then store these nulled indexes in another trash Array once the garbage count has reached a limit you've defined loop through the numerically sorted trash indexes deleting splices in bulk. This concept is demonstrated in Tweensy.
Nulling Object vs. Delete Object
delete一个对象的属性要比把该属性设置为null 更昂贵,所以对于对象的属性最好设置为null
Nesting Loops(嵌套循环)
多次嵌套循环效率差,所以最好保证循环在2层以内
Inline code vs. function references
如果在时间帧上的函数很长而且执行时间长,最好,把该函数分成多个小的函数执行。
这样可以缩短执行时间提高效率
Arguments vs. variable referencing
尽量最小化函数的参数个数
Function apply scoping do it or not?
Scoping function.apply is a little bit slower than not so if you don't have to then don't.
Array push vs. Array index
用设置index的方式来代替使用数组函数push
比如
list[list.length] = data; 要比直接用push快600%;
Array emptying - length 0 vs. A new Array
如果你需要设置一个空数组,有一个方便的办法去选择,就是通过设置它的length属性为0
或者你会认为这么做是不错的选择,原因是它能节省内存,但是事实上这样做的执行速度不如直接new array的效率高
当然,如果你需要在一次循环中清除多于510个数组为空时,用length设置为0的时候会更好
Var declarations on multiple lines vs. Var declarations on a single line
将变量声明在一行中,要比声明多行更好,效率更高
i.e.var a:int=0, b:int=0, c:int=0;
vs.var a:int=0;
var b:int=0;
var c:int=0;
如果你想去交换变量,但是又不想创建新的变量的时候,可以用xor 如:
Using Xor to swap variables
a = a^b;
b = a^b;
a = a^b;
Multiplication vs. Division
乘法的运算速率总是比出发快,比如5000/1000 要比 5000*0.001快130%;
When type casting the keyword 建议使用对应的类型的变量进行比较 同类型的比较效率高的多
Type casting comparison 强制转换类型对比
as
is 250% more efficient than casting by Type(item);
Though surprisingly not using either is about 1400% more efficient.
Long vs Short variable names
尽量用短的变量名