java ArrayList与LinkedList 使用for,forearch,Iterator的遍历效率

来源:互联网 发布:里诺仓库管理软件sql 编辑:程序博客网 时间:2024/05/29 16:17


public class test {


/**
* @param args
*/
public static void main(String[] args) {
ArrayList<Integer> al=new ArrayList<Integer>();
   
for(int i=0;i<900000;i++){
al.add(new Integer(4));
}
showForForInter(al);
showFor(al);
showForEach(al);
showIterator(al);

}

//for int 循环遍历
public static void showForForInter(ArrayList<Integer> al){
int no=al.size();
long start =System.nanoTime();
for(int j=0;j<no;j++){
al.get(j);
}
long end =System.nanoTime();
System.out.println("for int 循环遍历:"+(end- start) / (1000));
}
//for循环遍历
public  static void showFor( ArrayList<Integer> al){
//开始编译执行时间
long start =System.nanoTime();

for(int j=0;j<al.size();j++){
al.get(j);
}
//执行完后的时间
long end =System.nanoTime();
System.out.println("for循环遍历:"+(end- start) / (1000));
}

//foEach循环遍历
public static void showForEach(ArrayList<Integer> al){
//开始编译执行时间
long start =System.nanoTime();
for(int j:al){
al.get(j);
}
//执行完后的时间
long end =System.nanoTime();
System.out.println("forEach循环遍历:"+(end- start) / (1000));
}

//Iterator遍历
public static void showIterator(ArrayList<Integer> al){
//开始编译执行时间
long start =System.nanoTime();
Iterator<Integer> it=al.iterator();
while(it.hasNext()){
it.next();
}
//执行完后的时间
long end =System.nanoTime();
System.out.println("Iterator循环遍历:"+(end- start) / (1000));
}
/*
* 9000条
for int 循环遍历:3038
for循环遍历:3658
forEach循环遍历:10548
Iterator循环遍历:4752*/

/*900000条
for int 循环遍历:9277
for循环遍历:11022
forEach循环遍历:38093
Iterator循环遍历:17727*/

}

将ArrayList<Integer>换成===>LinkedList<Integer>

9000条

for循环遍历:64875
forEach循环遍历:5897
Iterator循环遍历:2803

    

从上述来看,则是for循环更快些(先将list长度赋值,这样不用每次遍历都需要机选list长度,效率高了一点);

但是如果将测试的ArrayList替换成LinkedList,再来执行一遍相同的代码,将会得到惊讶的结果:for循环的效率实在是太低了,让人都没有耐心等程序执行完成了。

上种情况的出现for比iterator快,是因为对于ArrayList索引直接取值快,随机访问速度是ArrayList的优势所在。
综上所述,还是尽量提倡用iterator来遍历集合效果会更加好点。


2 0
原创粉丝点击