今天String源码,看到了for循环的多种写法,闲来无事,测试一下for循环速度问题,下面是创建list对象,添加map,然后for循环list的所有集合,发现时间相差甚远,下面是最基础的代码,有大神解释一下,为什么吗?
public static void main(String[] args) {
List list = new LinkedList();
for (int i = 0; i < 1000000 ; i++) {
Map map = new HashMap();
list.add(map);
}
//开始for循环起始时间(纳秒)
long start = System.nanoTime();
/*
下面是五中写法
1.for (int i =0; i<list.size();i++) { }
2. for (int i =0; i<list.size();++i) { }
3. for (int i = list.size(); i-- > 0;) { }
4. for (int i = list.size(); i > 0;i--) { }
5. for (int i = list.size(); --i >= 0;) { }
*/
//for循环结束时间(纳秒)
long end = System.nanoTime();
//输出循环所需时间
System.out.println(end - start);
}
时间输出,
第1种for循环平均2035444纳秒左右
第2种for循环平均1955434纳秒左右
第3种for循环平均1215002纳秒左右
第4种for循环平均1195011纳秒左右
第5种for循环平均10075023纳秒左右
总结,第五种方法 for (int i = list.size(); --i >= 0;) { } 循环最快