java 比较几种常见循环方式的优劣
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt224
我们常用for循环,foeach,while等作为循环list或者数组的方式,但是大家有没有真正考虑过他们之间的性能差异呢,以下我来给大家分析下:
List<String> list = new ArrayList<String>();
for(int i=0;i<5000000;i++) {
list.add( "grefr");
}
long time1 = System.nanoTime();
for(int i = 0;i<5000000;i++) {
String str = list.get(i);
}
long time2 = System.nanoTime();
System. out.println("for循环使用时间" +(time2-time1));
long time3 = System.nanoTime();
for(String str:list) {
}
long time4 = System.nanoTime();
System. out.println("foreach循环使用时间" +(time4-time3));
long time5 = System. nanoTime();
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
String str = iterator.next();
}
long time6 = System.nanoTime();
System. out.println("迭代器循环使用时间" +(time6-time5 ));
long time7 = System.nanoTime();
for( Iterator<String> iterator2 = list.iterator();iterator2.hasNext();) {
String str = iterator2.next();
}
long time8 = System.nanoTime();
System. out.println("for改装的迭代器循环使用时间" +(time8-time7));
long time9 = System. nanoTime();
int i = -1;
while(i++<list.size()-1) {
String str = list.get(i);
}
long time10 = System. nanoTime();
System. out.println("while循环使用时间" +(time10-time9));
这段代码执行的结果是:
for循环使用时间 84835391
foreach循环使用时间 171477032
迭代器循环使用时间 175461419
for改装的迭代器循环使用时间 168014315
while循环使用时间 112974805
很显然,在遍历List时for循环的遍历效率要更高
但是在下面的遍历中,
int num = 1000000;
long time1 = System.nanoTime();
for(int i = 0;i<num;i++ ) {
}
long time2 = System.nanoTime();
System. out.println(time2-time1);
long time3 = System.nanoTime();
while(num-->0) {
}
long time4 = System.nanoTime();
System. out.println(time4-time3);
运行结果如下:
for循环执行时间为: 7163405
while循环执行时间为:3595701