将for (int i = 0; i (); i++)改为int j = list.size(); for (int i = 0; i ; i++),当数据量很大时list.size()消耗的额外性能也是可观的。 public class ListDemo { public static void main(String[] args) { ...
需要将for (int i = 0; i < list.size(); i++)改为int j = list.size(); for (int i = 0; i < j; i++)吗?
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()方法,优化后的方法还是要快一点,对于数据量大的列表还是推荐优化后的方法。
本站为非盈利网站,如果您喜欢这篇文章,欢迎支持我们继续运营!
本站主要用于日常笔记的记录和生活日志。本站不保证所有内容信息可靠!(大多数文章属于搬运!)如有版权问题,请联系我立即删除:“abcdsjx@126.com”。
QQ: 1164453243
邮箱: abcdsjx@126.com