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消耗多一點點時間似乎也無所謂。但是,另兩種代碼也不見得“不清晰”,呵呵。看著辦了。

          posted @ 2006-03-03 12:00 Raymond的Java筆記 閱讀(501) | 評論 (0)編輯 收藏
           
          主站蜘蛛池模板: 交口县| 垦利县| 屏山县| 佳木斯市| 称多县| 定日县| 文水县| 香河县| 壤塘县| 伊宁市| 漠河县| 那坡县| 大庆市| 明溪县| 明水县| 吴江市| 景宁| 渭南市| 南宁市| 固始县| 潜山县| 石柱| 黄陵县| 枞阳县| 邯郸县| 瑞丽市| 当阳市| 汉沽区| 德钦县| 靖宇县| 读书| 义乌市| 临夏县| 乾安县| 涟源市| 高台县| 大连市| 北碚区| 澄迈县| 澄城县| 济南市|