1 /**
2 * 測試For里變量對性能的影響;
3 *
4 * @author 老紫竹(laozizhu.com)
5 */
6 public class TestFor {
7 static int num = 100000000;
8
9 public static void main(String[] args) {
10
11 long begin = System.currentTimeMillis();
12 for (int i = 0; i < num; i++) {
13
14 }
15 long end = System.currentTimeMillis();
16 System.out.println(end - begin);
17
18 // 測試間接的屬性
19 // 影響很大
20 A a = new A();
21 begin = System.currentTimeMillis();
22 for (int i = 0; i < a.b.c.d.length; i++) {
23
24 }
25 end = System.currentTimeMillis();
26 System.out.println(end - begin);
27
28 // 測試直接的屬性
29 // 無影響
30 D d = new D();
31 begin = System.currentTimeMillis();
32 for (int i = 0; i < d.length; i++) {
33
34 }
35 end = System.currentTimeMillis();
36 System.out.println(end - begin);
37 }
38
39 static class A {
40 B b = new B();
41 }
42
43 static class B {
44 C c = new C();
45 }
46
47 static class C {
48 D d = new D();
49 }
50
51 static class D {
52 int length = num;
53 }
54 }
2 * 測試For里變量對性能的影響;
3 *
4 * @author 老紫竹(laozizhu.com)
5 */
6 public class TestFor {
7 static int num = 100000000;
8
9 public static void main(String[] args) {
10
11 long begin = System.currentTimeMillis();
12 for (int i = 0; i < num; i++) {
13
14 }
15 long end = System.currentTimeMillis();
16 System.out.println(end - begin);
17
18 // 測試間接的屬性
19 // 影響很大
20 A a = new A();
21 begin = System.currentTimeMillis();
22 for (int i = 0; i < a.b.c.d.length; i++) {
23
24 }
25 end = System.currentTimeMillis();
26 System.out.println(end - begin);
27
28 // 測試直接的屬性
29 // 無影響
30 D d = new D();
31 begin = System.currentTimeMillis();
32 for (int i = 0; i < d.length; i++) {
33
34 }
35 end = System.currentTimeMillis();
36 System.out.println(end - begin);
37 }
38
39 static class A {
40 B b = new B();
41 }
42
43 static class B {
44 C c = new C();
45 }
46
47 static class C {
48 D d = new D();
49 }
50
51 static class D {
52 int length = num;
53 }
54 }
運行結果
78
344
78
可見,如果只是簡單的 a.length, 那么與 len = a.length 直接用len沒有區別
但如果是多級,則有較大的影響了。