之前写代码,很少去考虑优化的问题,但是进几次的面试中,面试官都会偏向去问一些关于优化的问题。设计的优化,程序的优化等。
今天偶然写了一段小程序,测试了一下。如下:
package com.sgl.test; import java.util.ArrayList; import java.util.List; public class MainTest { public static void main(String[] args) { List<Integer> list=new ArrayList<>(); for (int i = 0; i < 10000; i++) { list.add(i); } long a=System.currentTimeMillis(); for (int i = 0; i < list.size(); i++) { System.out.println(1); } long b=System.currentTimeMillis(); long a1=System.currentTimeMillis(); for (int i = 0,size=list.size(); i < size; i++) { System.out.println(1); } long b1=System.currentTimeMillis(); System.out.println("-----"); System.out.println(b-a); System.out.println(b1-a1); } }
运行时间:
-----
312
249
当将次数在扩大100倍时:
-----
11204
10652
从程序上解释。时间少的代码块在于不用一直去计算列表的长度。