gpt4 book ai didi

java - 为什么for循环比while循环快

转载 作者:行者123 更新时间:2023-11-30 03:00:32 26 4
gpt4 key购买 nike

我最近开始学习java,我对此有点困惑——

下面的程序决定了for循环的速度--

public class ForLoopExample {
public static void main(String[] args) {
long startTime = System.nanoTime();
for(int a = 0; a < 10; a++) {
System.out.println(a);
}

long endTime = System.nanoTime();
System.out.println("for loop timing = " + (endTime - startTime) + " ns");
System.out.println("loop completed");
}
}

输出时序为:

for loop timing = 853716 ns

确定 while 循环速度的程序:

public class WhileLoopExample {
public static void main(String[] args) {
int a=0;
long startTime = System.nanoTime();
while(a < 10) {
System.out.println(a);
a++;
}
long endTime = System.nanoTime();
System.out.println("while loop timing = " + (endTime - startTime) + " ns");
}
}

while loop timing=928358 ns

Why does this happen a detailed explanation would be appreciated. 

最佳答案

重新运行超过十次迭代的测试,但也运行这些迭代的更多迭代,例如内循环中 10000 次,外循环中 10 次,并对结果进行平均。他们应该很接近。

存在差异的原因是操作系统和多线程的结果。操作系统正在管理除您的程序之外的许多任务,这些任务的优先级可能比您的程序稍高。这会导致您执行时的视觉延迟。

拥有更大的样本量应该会减少结果的方差。

关于java - 为什么for循环比while循环快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36128191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com