我是靠谱客的博主 俊秀小海豚,这篇文章主要介绍关于List的迭代器与FOR循环的见解,现在分享给大家,希望可以做个参考。

在项目的开发过程中,通常会对List进行遍历,常见的两种遍历方式为for循环和迭代器Iterator。

 

那么是用FOR循环效率高一些呢?还是用迭代器的效率高一些呢?

我的见解如下:

 

在内存中用来记录数据的存储方式有两种(此处不考虑Map),一种为顺序(即数组)存储形式,一种为链表的存储形式:

对于顺序存储形式,采用下标的形式来找到对应的记录;

对于链表存储形式,则是必须根据链表的指向一条一条的来定位数据;

 

所以For循环用于顺序存储结构的数据,Iterator则更适用于链表结构的数据。

 

而在我们的开发中,对于List这种集合,则有几点需要说明的:

List下面有几个常用的实现类如:ArrayList , LinkedList与Vector。

其中,ArrayList 与 Vector 的存储形式为数组,LinkedList则是取用的链表的结构。

 

所以从理论上来讲,ArrayList 与 Vector的遍历使用For循环效率高,LinkedList用Iterator效率高

 

下面是实验结果:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void main(String[] args) { List<String> stringList = new ArrayList<String>(); for(int i = 0 ; i < 5000000 ; i++){ stringList.add(String.valueOf(Math.random()%100)); } String str = ""; long start = System.currentTimeMillis(); Iterator<String> it = stringList.iterator(); while(it.hasNext()){ str = it.next(); } System.out.println("ArrayList 下 Iterator方式消耗时间:" + (System.currentTimeMillis()-start)); start = System.currentTimeMillis(); int length = stringList.size(); for(int i = 0 ; i < length ; i++){ str = stringList.get(i); } System.out.println("ArrayList 下 For方式消耗时间:" + (System.currentTimeMillis()-start)); }

 

结果如下

复制代码
1
2
ArrayList 下 Iterator方式消耗时间:57 ArrayList 下 For方式消耗时间:51

 

而在LinkedList下:

Iterator的效率是for循环的百倍不止,在此就不作列举。(因为在100W的数据量下,我机器跑了几十分钟都还没有运算完,足以可见在链表的存储结构下还是Iterator效率最高)

 

最后

以上就是俊秀小海豚最近收集整理的关于关于List的迭代器与FOR循环的见解的全部内容,更多相关关于List内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部