1、用乘法来代替除法(当除数可转化为有限数的时候)。比如var n:Number = value *0.5;要比var n:Number = value / 2;快。但差别并不是很大。只有在需要大量计算情况下,比如3D引擎中差别才比较明显。
2、用位运算代替除2或乘2。比如10>>1要比10*2快,而10<<1要比10*2快。从测试来看位运算几乎比乘除快一倍,但是一般情况下,我们不能选择位运算,比如我们就不能用13>>1来代替13/2,尽管前者比后者运算速度更快,但2者的运算结果却不一样。所以还是要看具体情况。
3、用unit()或int()代替取整运算Math.floor()和Math.ceil()。比如var test:uint = uint(1.5);要比var test:Number = Math.floor(1.5);快;而var test:uint = uint(1.5)+1;要比var test:Number = Math.ceil(1.5);也快。如果是Math.floor(),还可以用位运算(>>0)来代替。比如var test:uint =1.5>>0,比unit()或int()更快。
4、用乘-1来代替Math.abs()方法。比如var nn:Number = -23;var test:Number= nn < 0 ? nn * -1 : nn;要比var nn:Number = -23;var test:Number = Math.abs(nn);快。
当然还有更多的优化计算的方法。一般来说,低级运算要比高级运算速度;内部方法比调用其他方法速度快。另外要注意的是,这些方法有的时候可能并一定适用。
附上测试代码:
2
3 var time:Number = getTimer();
4
5 function runDivisionTest():void
6 {
7 time = getTimer();
8 for (var i:Number = 0; i < 10000000; i++)
9 {
10 var test:Number = i / 2;
11 }
12
13 trace("DivisionTest: ", (getTimer() - time));
14 }
15
16 function runMultTest():void
17 {
18 time = getTimer();
19 for (var i:Number = 0; i < 10000000; i++)
20 {
21 var test:Number = i * .5;
22 }
23 trace("MultTest: ", (getTimer() - time));
24 }
25
26 function runBitTest():void
27 {
28 time = getTimer();
29 for (var i:int = 0; i < 10000000; i++)
30 {
31 var test:int = i >> 1;
32 }
33 trace("BitTest: ", (getTimer() - time));
34 }
35
36 function runFloorTest():void
37 {
38 time = getTimer();
39 for (var i:uint = 0; i < 10000000; i++)
40 {
41 var n:Number = 1.5;
42 var test:Number = Math.floor(n);
43 }
44 trace("FloorTest: ", (getTimer() - time));
45 }
46
47 function runUintTest():void
48 {
49 time = getTimer();
50 for (var i:uint = 0; i < 10000000; i++)
51 {
52 var n:Number = 1.5;
53 var test:uint = uint(n);
54 }
55 trace("UintTest: ", (getTimer() - time));
56 }
57
58 function runCeilTest():void
59 {
60 time = getTimer();
61 for (var i:uint = 0; i < 10000000; i++)
62 {
63 var n:Number = 1.5;
64 var test:Number = Math.ceil(n);
65 }
66 trace("CeilTest: ", (getTimer() - time));
67 }
68
69 function runUintCeilTest():void
70 {
71 time = getTimer();
72 for (var i:uint = 0; i < 10000000; i++)
73 {
74 var n:Number = 1.5;
75 var test:uint = n == uint(n) ? n : uint(n) + 1;
76 }
77 trace("UintCeilTest: ", (getTimer() - time));
78 }
79
80 function runABSTest():void
81 {
82 time = getTimer();
83 for (var i:uint = 0; i < 10000000; i++)
84 {
85 var n:Number = -1.5;
86 var test:Number = Math.abs(n);
87 }
88 trace("ABSTest: ", (getTimer() - time));
89 }
90
91 function runABSMultTest():void
92 {
93 time = getTimer();
94 for (var i:uint = 0; i < 10000000; i++)
95 {
96 var n:Number = -1.5;
97 var test:Number = n < 0 ? n * -1 : n;
98 }
99 trace("ABSMultTest: ", (getTimer() - time));
100
101 }
102
103 runDivisionTest();
104
105 runMultTest();
106
107 runBitTest();
108
109 runFloorTest();
110
111 runUintTest();
112
113 runCeilTest();
114
115 runUintCeilTest();
116
117 runABSTest();
118
119 runABSMultTest();