在进行迭代的时候,程序运行的效率也是我们挑选迭代方法的重要原因。目前有三种迭代方法:for循环、迭代器和Foreach。前两者相信大家都非常熟悉,为了更加直观分析效率的不同,我们还加入Foreach一起比较。下面我们就三种方法的概念进行理解,然后ArrayList中探索三种方法的效率。
1.概念理解
for循环:是支持迭代的一种通用结构,是最有效,最灵活的循环结构
迭代器:是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的
Foreach:通过阅读源码我们还发现一个Iterable接口。它包含了一个产生Iterator对象的iterator()方法,而且将Iterator对象被foreach用来在序列中移动。对于任何实现Iterable接口的对象都可以使用。
2.效率实例
ArrayList中的效率对比:Listintegers=Lists.newArrayList();
for(inti=0;i<100000;i++){
integers.add(i);
}
longstart1=System.currentTimeMillis();
for(intcount=0;count<10;count++){
for(inti=0;i
intj=integers.get(i);
}
}
System.out.println(String.format("for循环100次时间:%sms",System.currentTimeMillis()-start1));
longstart2=System.currentTimeMillis();
for(intcount=0;count<10;count++){
for(Integeri:integers){
intj=i;
}
}
System.out.println(String.format("foreach循环100次时间:%sms",System.currentTimeMillis()-start2));
longstart3=System.currentTimeMillis();
for(intcount=0;count<10;count++){
Iteratoriterator=integers.iterator();
while(iterator.hasNext()){
intj=iterator.next();
}
}
System.out.println(String.format("迭代器循环100次时间:%sms",System.currentTimeMillis()-start3));
结果:for循环100次时间:15ms
foreach循环100次时间:25ms
迭代器循环100次时间:20ms
ArrayList下三者效率差不多,for循环最优,因为ArrayList通过数组来实现,数组通过索引来定位的时间复杂度是O(1),1次就能定位到,所以效率非常高。
总结:for循环便于访问顺序存储的记录,而foreach和迭代器便于访问链接存储。
以上就是java迭代器和for循环优劣的分析,可以看出for循环作为我们最常用的知识点,在使用效率上是最高的。不过在访问链接存储的用处上,还是推荐大家使用其它两种方法。
如果觉得《python迭代器和for循环区别_java迭代器和for循环优劣》对你有帮助,请点赞、收藏,并留下你的观点哦!