ArrayList和LinkedList遍历方式及性能对比分析
2015-10-07 00:39
519 查看
ArrayList和LinkedList的几种循环遍历方式及性能对比分析
主要介绍ArrayList和LinkedList这两种list的五种循环遍历方式,各种方式的性能测试对比,根据ArrayList和LinkedList的源码实现分析性能结果,总结结论。通过本文你可以了解(1)List的五种遍历方式及各自性能 (2)foreach及Iterator的实现 (3)加深对ArrayList和LinkedList实现的了解。
阅读本文前希望你已经了解ArrayList顺序存储和LinkedList链式的结构,本文不对此进行介绍。
相关:HashMap循环遍历方式及其性能对比
1. List的五种遍历方式
下面只是简单介绍各种遍历示例(以ArrayList为例),各自优劣会在本文后面进行分析给出结论。
(1) for each循环
Java
List<Integer> list = new ArrayList<Integer>();
for (Integer j : list) {
// use j
}
1 2 3 4 | List<Integer>list=newArrayList<Integer>(); for(Integerj:list){ // use j } |
Java
List<Integer> list = new ArrayList<Integer>();
for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext();) {
iterator.next();
}
1 2 3 4 | List<Integer>list=newArrayList<Integer>(); for(Iterator<Integer>iterator=list.iterator();iterator.hasNext();){ iterator.next(); } |
Java
List<Integer> list = new ArrayList<Integer>();
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
}
1 2 3 4 5 | List<Integer>list=newArrayList<Integer>(); Iterator<Integer>iterator=list.iterator(); while(iterator.hasNext()){ iterator.next(); } |
Java
List<Integer> list = new ArrayList<Integer>();
for (int j = 0; j < list.size(); j++) {
list.get(j);
}
1 2 3 4 | List<Integer>list=newArrayList<Integer>(); for(intj=0;j<list.size();j++){ list.get(j); } |
Java
List<Integer> list = new ArrayList<Integer>();
int size = list.size();
for (int j = 0; j < size; j++) {
list.get(j);
}
1 2 3 4 5 | List<Integer>list=newArrayList<Integer>(); intsize=list.size(); for(intj=0;j<size;j++){ list.get(j); } |
Java
List<Integer> list = new ArrayList<Integer>();
for (int j = list.size() - 1; j >= 0; j--) {
list.get(j);
}
1 2 3 4 | List<Integer>list=newArrayList<Integer>(); for(intj=list.size()-1;j>=0;j--){ list.get(j); } |
2、List五种遍历方式的性能测试及对比
以下是性能测试代码,会输出不同数量级大小的ArrayList和LinkedList各种遍历方式所花费的时间。
ArrayList和LinkedList循环性能对比测试代码
PS:如果运行报异常in thread “main” java.lang.OutOfMemoryError: Java heap space,请将main函数里面list size的大小减小。
其中getArrayLists函数会返回不同size的ArrayList,getLinkedLists函数会返回不同size的LinkedList。
loopListCompare函数会分别用上面的遍历方式1-5去遍历每一个list数组(包含不同大小list)中的list。
print开头函数为输出辅助函数。
测试环境为Windows7 32位系统 3.2G双核CPU 4G内存,Java 7,Eclipse -Xms512m -Xmx512m
最终测试结果如下:
compare loop performance of ArrayList
-----------------------------------------------------------------------
list size | 10,000 | 100,000 | 1,000,000 | 10,000,000
-----------------------------------------------------------------------
for each | 1 ms | 3 ms | 14 ms | 152 ms
-----------------------------------------------------------------------
for iterator | 0 ms | 1 ms | 12 ms | 114 ms
-----------------------------------------------------------------------
for list.size() | 1 ms | 1 ms | 13 ms | 128 ms
-----------------------------------------------------------------------
for size = list.size() | 0 ms | 0 ms | 6 ms | 62 ms
-----------------------------------------------------------------------
for j-- | 0 ms | 1 ms | 6 ms | 63 ms
-----------------------------------------------------------------------
compare loop performance of LinkedList
-----------------------------------------------------------------------
list size | 100 | 1,000 | 10,000 | 100,000
-----------------------------------------------------------------------
for each | 0 ms | 1 ms | 1 ms | 2 ms
-----------------------------------------------------------------------
for iterator | 0 ms | 0 ms | 0 ms | 2 ms
-----------------------------------------------------------------------
for list.size() | 0 ms | 1 ms | 73 ms | 7972 ms
-----------------------------------------------------------------------
for size = list.size() | 0 ms | 0 ms | 67 ms | 8216 ms
-----------------------------------------------------------------------
for j-- | 0 ms | 1 ms | 67 ms | 8277 ms
-----------------------------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | compare loop performance of ArrayList ----------------------------------------------------------------------- list size |10,000 |100,000 |1,000,000|10,000,000 ----------------------------------------------------------------------- foreach |1ms |3ms |14ms |152ms ----------------------------------------------------------------------- foriterator |0ms |1ms |12ms |114ms ----------------------------------------------------------------------- forlist.size() |1ms |1ms |13ms |128ms ----------------------------------------------------------------------- forsize=list.size()|0ms |0ms |6ms |62ms ----------------------------------------------------------------------- forj-- |0ms |1ms |6ms |63ms ----------------------------------------------------------------------- compare loop performance of LinkedList ----------------------------------------------------------------------- list size |100 |1,000 |10,000 |100,000 ----------------------------------------------------------------------- foreach |0ms |1ms |1ms |2ms ----------------------------------------------------------------------- foriterator |0ms |0ms |0ms |2ms ----------------------------------------------------------------------- forlist.size() |0ms |1ms |73ms |7972ms ----------------------------------------------------------------------- forsize=list.size()|0ms |0ms |67ms |8216ms ----------------------------------------------------------------------- forj-- |0ms |1ms |67ms |8277ms ----------------------------------------------------------------------- |
表横向为同一遍历方式不同大小list遍历的时间消耗,纵向为同一list不同遍历方式遍历的时间消耗。
PS:由于首次遍历List会稍微多耗时一点,for each的结果稍微有点偏差,将测试代码中的几个Type顺序调换会发现,for each耗时和for iterator接近。
3、遍历方式性能测试结果分析
(1) foreach介绍
foreach是Java SE5.0引入的功能很强的循环结构,for (Integer j : list)应读作for each int in list。
for (Integer j : list)实现几乎等价于
Java
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
Integer j = iterator.next();
}
1 2 3 4 | Iterator<Integer>iterator=list.iterator(); while(iterator.hasNext()){ Integerj=iterator.next(); } |
这时我们已经发现foreach的一大好处,简单一行实现了四行的功能,使得代码简洁美观,另一大好处是相对于下标循环而言的,foreach不必关心下标初始值和终止值及越界等,所以不易出错。Effective-Java中推荐使用此种写法遍历,本文会验证这个说法。
使用foreach结构的类对象必须实现了Iterable接口,Java的Collection继承自此接口,List实现了Collection,这个接口仅包含一个函数,源码如下:
Java
package java.lang;
import java.util.Iterator;
/**
* Implementing this interface allows an object to be the target of
* the "foreach" statement.
*
* @param <T> the type of elements returned by the iterator
*
* @since 1.5
*/
public interface Iterable<T> {
/**
* Returns an iterator over a set of elements of type T.
*
* @return an Iterator.
*/
Iterator<T> iterator();
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | packagejava.lang; importjava.util.Iterator; /** * Implementing this interface allows an object to be the target of * the "foreach" statement. * * @param <T> the type of elements returned by the iterator * * @since 1.5 */ publicinterfaceIterable<T>{ /** * Returns an iterator over a set of elements of type T. * * @return an Iterator. */ Iterator<T>iterator(); } |
Java
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
1 2 3 4 5 6 7 | publicinterfaceIterator<E>{ booleanhasNext(); Enext(); voidremove(); } |
compare loop performance of ArrayList
-----------------------------------------------------------------------
list size | 10,000 | 100,000 | 1,000,000 | 10,000,000
-----------------------------------------------------------------------
for each | 1 ms | 3 ms | 14 ms | 152 ms
-----------------------------------------------------------------------
for iterator | 0 ms | 1 ms | 12 ms | 114 ms
-----------------------------------------------------------------------
for list.size() | 1 ms | 1 ms | 13 ms | 128 ms
-----------------------------------------------------------------------
for size = list.size() | 0 ms | 0 ms | 6 ms | 62 ms
-----------------------------------------------------------------------
for j-- | 0 ms | 1 ms | 6 ms | 63 ms
-----------------------------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | compare loop performance of ArrayList ----------------------------------------------------------------------- list size |10,000 |100,000 |1,000,000|10,000,000 ----------------------------------------------------------------------- foreach |1ms |3ms |14ms |152ms ----------------------------------------------------------------------- foriterator |0ms |1ms |12ms |114ms ----------------------------------------------------------------------- forlist.size() |1ms |1ms |13ms |128ms ----------------------------------------------------------------------- forsize=list.size()|0ms |0ms |6ms |62ms ----------------------------------------------------------------------- forj-- |0ms |1ms |6ms |63ms ----------------------------------------------------------------------- |
从上面我们可以看出:
a. 在ArrayList大小为十万之前,五种遍历方式时间消耗几乎一样
b. 在十万以后,第四、五种遍历方式快于前三种,get方式优于Iterator方式,并且
Java
int size = list.size();
for (int j = 0; j < size; j++) {
list.get(j);
}
1 2 3 4 | intsize=list.size(); for(intj=0;j<size;j++){ list.get(j); } |
Java
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
……
}
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | privateclassItrimplementsIterator<E>{ intcursor; // index of next element to return intlastRet=-1;// index of last element returned; -1 if no such intexpectedModCount =modCount; publicbooleanhasNext(){ returncursor!=size; } @SuppressWarnings("unchecked") publicEnext(){ checkForComodification(); inti=cursor; if(i>=size) thrownewNoSuchElementException(); Object[]elementData=ArrayList.this.elementData; if(i>=elementData.length) thrownewConcurrentModificationException(); cursor=i+1; return(E)elementData[lastRet=i]; } …… } publicEget(intindex){ rangeCheck(index); returnelementData(index); } |
c . 从上可以看出即便在千万大小的ArrayList中,几种遍历方式相差也不过50ms左右,且在常用的十万左右时间几乎相等,考虑foreach的优点,我们大可选用foreach这种简便方式进行遍历。
(3) LinkedList遍历方式结果分析
compare loop performance of LinkedList
-----------------------------------------------------------------------
list size | 100 | 1,000 | 10,000 | 100,000
-----------------------------------------------------------------------
for each | 0 ms | 1 ms | 1 ms | 2 ms
-----------------------------------------------------------------------
for iterator | 0 ms | 0 ms | 0 ms | 2 ms
-----------------------------------------------------------------------
for list.size() | 0 ms | 1 ms | 73 ms | 7972 ms
-----------------------------------------------------------------------
for size = list.size() | 0 ms | 0 ms | 67 ms | 8216 ms
-----------------------------------------------------------------------
for j-- | 0 ms | 1 ms | 67 ms | 8277 ms
-----------------------------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | compare loop performance of LinkedList ----------------------------------------------------------------------- list size |100 |1,000 |10,000 |100,000 ----------------------------------------------------------------------- foreach |0ms |1ms |1ms |2ms ----------------------------------------------------------------------- foriterator |0ms |0ms |0ms |2ms ----------------------------------------------------------------------- forlist.size() |0ms |1ms |73ms |7972ms ----------------------------------------------------------------------- forsize=list.size()|0ms |0ms |67ms |8216ms ----------------------------------------------------------------------- forj-- |0ms |1ms |67ms |8277ms ----------------------------------------------------------------------- |
从上面我们可以看出:
a 在LinkedList大小接近一万时,get方式和Iterator方式就已经差了差不多两个数量级,十万时Iterator方式性能已经远胜于get方式。
我们看看LinkedList中迭代器和get方法的实现
Java
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned = null;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
……
}
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
/**
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | privateclassListItrimplementsListIterator<E>{ privateNode<E>lastReturned=null; privateNode<E>next; privateintnextIndex; privateintexpectedModCount=modCount; ListItr(intindex){ // assert isPositionIndex(index); next=(index==size)?null:node(index); nextIndex=index; } publicbooleanhasNext(){ returnnextIndex<size; } publicEnext(){ checkForComodification(); if(!hasNext()) thrownewNoSuchElementException(); lastReturned=next; next=next.next; nextIndex++; returnlastReturned.item; } …… } publicEget(intindex){ checkElementIndex(index); returnnode(index).item; } /** * Returns the (non-null) Node at the specified element index. */ Node<E>node(intindex){ // assert isElementIndex(index); if(index<(size>>1)){ Node<E>x=first; for(inti=0;i<index;i++) x=x.next; returnx; }else{ Node<E>x=last; for(inti=size-1;i>index;i--) x=x.prev; returnx; } } |
所以对于LinkedList的遍历推荐使用foreach,避免使用get方式遍历。
(4) ArrayList和LinkedList遍历方式结果对比分析
从上面的数量级来看,同样是foreach循环遍历,ArrayList和LinkedList时间差不多,可将本例稍作修改加大list size会发现两者基本在一个数量级上。
但ArrayList get函数直接定位获取的方式时间复杂度为O(1),而LinkedList的get函数时间复杂度为O(n)。
再结合考虑空间消耗的话,建议首选ArrayList。对于个别插入删除非常多的可以使用LinkedList。
4、结论总结
通过上面的分析我们基本可以总结下:
(1) 无论ArrayList还是LinkedList,遍历建议使用foreach,尤其是数据量较大时LinkedList避免使用get遍历。
(2) List使用首选ArrayList。对于个别插入删除非常多的可以使用LinkedList。
(3) 可能在遍历List循环内部需要使用到下标,这时综合考虑下是使用foreach和自增count还是get方式。
相关文章推荐
- ArrayList和LinkedList遍历方式及性能对比分析
- android(基于监听)的事件处理
- Combination Sum II
- [hiho]#1079 : 离散化 线段树
- Apple Watch初体验
- NIO实例
- MySQL初步笔记,有待整理
- VHDL实现加法器
- while倒数阶乘的和
- php5.2.17 升级php-5.6.14
- Kinect2.0+Opencv获取高清面部信息
- JAVA中关于主方法调用非静态方法的问题
- Placement Test #2 Kyle’s Book Stack
- 灰度直方图均衡化的算数推导
- 校验码(海明校验,CRC冗余校验,奇偶校验)
- zepto 里的高宽
- 03SQLite的增删改查(Google提供的API)
- CentOS7 配置网卡
- Servlet处理应用
- RET2LIBC 练习(3) -- VIRTUALALLOC