Raymond
          Java筆記

          2006年3月3日

          在Java高效編程里面看到變量一個ArrayList的時候,有兩種方式:
          假設a是個ArrayList

          1、 for (int i=0;i<a.size();i++) {
          2、 for (int i=0,n=a.size();i<n;i++) {

          帶著點懷疑我做了一下試驗,的確是方法2快一點的,估計是a.size()方法里面花費了一點多余的時間。后來我想到jdk 1.5開始還有一種遍歷的for/each方法,我做了一下比較,結果有點驚訝。

          源程序如下

           1import java.util.ArrayList;
           2
           3public class ProfileArrayList {
           4
           5  public static void main(String[] args) {
           6    ArrayList<String> s=new ArrayList<String>();
           7    for (int i=0;i<15000;i++{
           8      s.add(""+System.currentTimeMillis());
           9    }

          10    System.out.println("Start ");
          11    testOne(s);
          12    testTwo(s);
          13    testThree(s);
          14    System.out.println("End ");
          15  }

          16  
          17  private static void testOne(ArrayList<String> a) {
          18    int j=0;String s=null;
          19    for (int i=0;i<a.size();i++{
          20      s=a.get(i);
          21      j++;
          22    }

          23  }

          24  
          25private static void testTwo(ArrayList<String> a) {
          26    int j=0;
          27    String s=null;
          28    for (int i=0,n=a.size();i<n;i++{
          29      s=a.get(i);
          30      j++;
          31    }

          32  }

          33
          34private static void testThree(ArrayList<String> a) {
          35  int j=0;
          36  for (String s : a) {
          37    j++;
          38  }

          39}

          40
          41}

          42

          通過Profiling工具看結果:
          方法      運行時間
          testOne   0.055764
          testTwo  0.043821
          testThres 0.132451

          也就是說,jdk 1.5的for/each循環是最慢的。有點不相信。開頭覺得是因為賦值造成的,但后來在另兩個方法里面加上賦值語句,依然是for/each最慢。比較有趣的結果。

          從代碼清晰角度,用for/each消耗多一點點時間似乎也無所謂。但是,另兩種代碼也不見得“不清晰”,呵呵??粗k了。

          posted @ 2006-03-03 12:00 Raymond的Java筆記 閱讀(498) | 評論 (0)編輯 收藏
           
          主站蜘蛛池模板: 蓬溪县| 错那县| 合肥市| 渝北区| 陇西县| 疏勒县| 阳谷县| 铜山县| 竹北市| 安达市| 合江县| 曲麻莱县| 界首市| 汽车| 伊金霍洛旗| 葵青区| 吉林省| 南丹县| 雷山县| 延庆县| 玉田县| 高碑店市| 沙河市| 乃东县| 璧山县| 大埔县| 莱阳市| 建瓯市| 高清| 盈江县| 南阳市| 永寿县| 德昌县| 灵璧县| 青海省| 阜南县| 都安| 内黄县| 昆明市| 乌什县| 芮城县|