此代码按预期打印“平均运行次数:0.99864197”
import java.util.Random;
public class A {
public static void main(String[] args) {
int min = -30;
int max = 1;
test(min, max);
}
static void test(int min, int max){
int count = 0;
Random rand = new Random(0);
for(int j = 0; j < 2097152; j++){
int number = min + rand.nextInt(max-min+1);
for(int i = 0; i < number; ++i) {
System.out.print("");
count++;
}
}
System.out.println("Average Number of Runs: " + count/65536F);
}
}
这段代码本应打印出完全相同的数字,但它却打印出一个随机的负数。
import java.util.Random;
public class A {
public static void main(String[] args) {
int min = -30;
int max = 1;
test(min, max);
}
static void test(int min, int max){
int count = 0;
Random rand = new Random(0);
for(int j = 0; j < 2097152; j++){
int number = min + rand.nextInt(max-min+1);
for(int i = 0; i < number; ++i) {
//System.out.print("");
count++;
}
}
System.out.println("Average Number of Runs: " + count/65536F);
}
}
Java 中的 for 循环是否有一些优化?
注意事项:
- 我使用的是 jdk1.6.0_45。
- 在正常使用中,新的 Random 会有更好的种子。
- min 和 max 应该可以是任何数字。
最佳答案
我认为这是 Java 6 某些版本中非常紧密循环的 JIT 处理中的一个错误。它可能是bug 6196102。或错误 6357124 .
更新到 Java 7 应该可行,但我知道这对您的情况没有多大帮助。您可能会发现在循环中添加“看起来它不是空操作,但会做一些您不关心的事情”方法调用也可以解决问题。例如,您可以对 i
的所有值求和,然后将其打印到某个诊断日志中以供忽略。
关于java - 接近空的 Java For-Loop 行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18040592/