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