Home > Java > javaTutorial > body text

Java uses ArrayList traversal and efficiency comparison example analysis

高洛峰
Release: 2017-01-22 15:55:39
Original
1607 people have browsed it

The examples in this article describe Java's use of ArrayList traversal and efficiency comparison. Share it with everyone for your reference. The details are as follows:

ArrayList arrL = new ArrayList();
ArrayList arrLTmp1 = new ArrayList();
ArrayList arrLTmp2 = new ArrayList();
ArrayList arrLTmp3 = new ArrayList();
ArrayList arrLTmp4 = new ArrayList();
for (int i=0;i<1000000;i++){
  arrL.add("第"+i+"个");
}
long t1 = System.nanoTime();
//方法1
Iterator it = arrL.iterator();
while(it.hasNext()){
  arrLTmp1.add(it.next());
}
long t2 = System.nanoTime();
//方法2
for(Iterator it2 = arrL.iterator();it2.hasNext();){
  arrLTmp2.add(it2.next());
}
long t3 = System.nanoTime();
//方法3
for (String vv :arrL){
  arrLTmp3.add(vv);
}
long t4 = System.nanoTime();
//方法4
for(int i=0;i
  arrLTmp4.add(arrL.get(i));
}
long t5 = System.nanoTime();
System.out.println("第一种方法耗时:" + (t2-t1)/1000 + "微秒");
System.out.println("第二种方法耗时:" + (t3-t2)/1000 + "微秒");
System.out.println("第三种方法耗时:" + (t4-t3)/1000 + "微秒");
System.out.println("第四种方法耗时:" + (t5-t4)/1000 + "微秒");
Copy after login

Output result:

第一种方法耗时:143069微秒
第二种方法耗时:381666微秒
第三种方法耗时:125909微秒
第四种方法耗时:63693微秒
Copy after login

Change the above 1000000 to 10 , the output result is:

第一种方法耗时:307微秒
第二种方法耗时:14微秒
第三种方法耗时:14微秒
第四种方法耗时:14微秒
Copy after login

I hope this article will be helpful to everyone’s java programming.

For more java using ArrayList traversal and efficiency comparison example analysis and related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template