您的位置:首页 > 编程语言 > Java开发

哪一种java循环方式性能最高

2016-11-08 14:54 573 查看
public class LoopTest {
private static List<Integer> list = new ArrayList<Integer>(1000000);

static {
for (int i = 0; i < 10000000; i++) {
list.add(i);
}
}

public void test(){
long startTime;
long endTime;

//style1
startTime = System.nanoTime();
for (int i : list) {
}
endTime = System.nanoTime();
System.out.println("style1 —— for(int i : list) —— " + (endTime - startTime) + "毫微秒");

//style2
startTime = System.nanoTime();
for (int i = 0; i < list.size(); i++) {
}
endTime = System.nanoTime();
System.out.println("style2 —— for(int i = 0; i < list.size(); i++) —— " + (endTime - startTime) + "毫微秒");

//style3
startTime = System.nanoTime();
int size = list.size();
for (int i = 0; i < size; i++) {
}
endTime = System.nanoTime();
System.out.println("style3 —— for(int i = 0; i < size; i++) —— " + (endTime - startTime) + "毫微秒");

//style4
startTime = System.nanoTime();
for (int i = list.size() - 1; i > -1; i--) {
}
endTime = System.nanoTime();
System.out.println("Style4 —— for(int i = list.size() - 1; i > -1; i--) —— " + (endTime - startTime) + "毫微秒");

}

public static void main(String[] args) {
new LoopTest().test();
}
}


输出结果:

style1 —— for(int i : list) —— 39563185毫微秒

style2 —— for(int i = 0; i < list.size(); i++) —— 5012893毫微秒

style3 —— for(int i = 0; i < size; i++) —— 3683956毫微秒

Style4 —— for(int i = list.size() - 1; i > -1; i–)—— 3199474毫微秒

结论:

style1性能最低,原因增强的for循环内部使用了迭代iterator 形式,创建interator和调用interator.get() 都需要时间。

style2是程序员最常用的循环方式,性能一般,原因在于list.size()做为循环判断的标准,每次循环都要比较一次(没有意义)。

style3和style4性能差不多,单位是”毫微秒”,1秒=1000豪秒;1毫秒=1000微秒;1微秒=1000毫微秒。

style4性能最高,实践说明一切! 可有一个问题,经过多次测试发现style4不稳定,消耗时间偶尔会超过style3。

推荐:

style3和style4性能相差不多,style4不稳定,而且用style4有些时候会导致代码的可读性差。so,我推荐style3,JDK源码里也采用了style3。

int size = list.size();
for (int i = 0; i < size; i++) {
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息