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 }
运行结果
78
344
78
可见,如果只是简单的 a.length, 那么与 len = a.length 直接用len没有区别
但如果是多级,则有较大的影响了。
	
posted on 2009-03-27 07:20 
老紫竹 阅读(1703) 
评论(3)  编辑  收藏