List是集合框架中使用度非常高的集合,在使用过程中经常会对List进行遍历,取得其中的值打印或者作其他操作。常用的有迭代器,foreach循环,for循环,stream来遍历List,但是他们的效率是大不一样的,来看看!
/*使用迭代器去遍历*/
long time1 = System.nanoTime();
Iterator<ApiResponse> iterator = spiderResults.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("Iterater程序耗时:"+(System.nanoTime()-time1)+" ms");
/*使用foreach循环去遍历*/
long time2 = System.nanoTime();
for(ApiResponse i:spiderResults)
{
}
System.out.println("Foreach程序耗时:"+(System.nanoTime()-time2)+" ms");
/*使用for循环遍历*/
long time3 = System.nanoTime();
for(int l=0;l<spiderResults.size();l++){
ApiResponse o = spiderResults.get(l);
}
System.out.println("For循环程序耗时:"+(System.nanoTime()-time3)+" ms");
/*使用Stream遍历*/
long time4 = System.nanoTime();
spiderResults.stream().forEach(x->{
Object o = x;
});
System.out.println("Stream程序耗时:"+(System.nanoTime()-time4)+" ms"); Iterater程序耗时:478300 ms Foreach程序耗时:26800 ms For循环程序耗时:14500 ms Stream程序耗时:6849100 ms
Iterater程序耗时:1720200 ms Foreach程序耗时:82200 ms For循环程序耗时:43800 ms Stream程序耗时:6445500 ms
Iterater程序耗时:883000 ms Foreach程序耗时:42800 ms For循环程序耗时:35400 ms Stream程序耗时:10080900 ms
由此可见,普通For循环的效率最快,Stream速度最慢。(效率由高到低)
for>foreach>iterater>stream