需要将for (int i = 0; i < list.size(); i++)改为int j = list.size(); for (int i = 0; i < j; i++)吗?

text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
public class ListDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>();
      int x = 10000000;
      while (x > 0) {
         list.add(x);
         x--;
      }
      test1(list);
      test2(list);
   }

   /**
    * 优化前
    *
    * @param list
    */
   public static void test1(List<Integer> list) {
      long before = System.currentTimeMillis();
      int count = 0;
      for (int i = 0; i < list.size(); i++) { 
         count = count + i;
      }
      long after = System.currentTimeMillis();
      System.out.println(after - before);
   }

   /**
    * 优化后
    *
    * @param list
    */
   public static void test2(List<Integer> list) {
      long before = System.currentTimeMillis();
      int count = 0;
      int j = list.size();
      for (int i = 0; i < j; i++) {
         count = count + i;
      }
      long after = System.currentTimeMillis();
      System.out.println(after - before);
   }
}

根据打印结果简单的对比下,发现虽然优化后会比优化前快,但是并没有很大的差别,这是因为List的size()方法返回的是List内部维护的尺寸变量size,代码如下:
public int size() {
return size;
}
并不是重新计算,当然相比于每次调用size()方法,优化后的方法还是要快一点,对于数据量大的列表还是推荐优化后的方法。

原文地址:https://blog.csdn.net/xyc_csdn/article/details/69665918?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168474993716782425192019%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168474993716782425192019&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-3-69665918-null-null.142^v87^insert_down1,239^v2^insert_chatgpt&utm_term=java%E4%BC%98%E5%8C%96