我尝试了以下代码:
public class Test {
public static void main(String[] args) {
int x = 9, y = 9, z = 0;
long startTime = System.currentTimeMillis();
// System.out.println("loop one start time = " + startTime);
for (int i = 0; i < 10000; i++) {
for (int j = 0; j < 10000; j++) {
z = x + y;
}
}
System.out.println("loop one use time = " + (System.currentTimeMillis() - startTime) + ",z = " + z);
startTime = System.currentTimeMillis();
// System.out.println("loop two start time = " + startTime);
for (int i = 0; i < 10000; i++) {
for (int j = 0; j < 10000; j++) {
z = sum(x, y);
}
}
System.out.println("loop two use time = " + (System.currentTimeMillis() - startTime) + ",z = " + z);
}
public static int sum(int x, int y) {
int t;
t = x + y;
return t;
}
}
控制台的输出是:
loop one use time = 216,z = 18
loop two use time = 70,z = 18.
似乎第二个循环比第一个循环花费的时间更少!我不明白为什么会这样。谢谢你的帮助。
更新:我交换了两个循环,现在循环一个需要更少的时间!!
loop two use time = 219,z = 18
loop one use time = 69,z = 18