This article suggests otherwise. But there is still a need to evaluate the loop condition. Does java just employ a specific trick to recognize this case?
5 回答
Check out the follow-up story to the article you quote.
NOTE to people answering: It appears the OP is asking about the .NET JIT, not the Java JIT, since the article referenced suggested that Java did a better job of (or that only Java did) optimizing away empty loops.
EDIT: Googling for more answers, Jon Skeet's name keeps coming up. See, for example, this thread on C# optimizations. Thus, when he answers, we'll have the authoritative answer! :-)
Yes it will.
http://www.javaspecialists.eu/archive/Issue158.html
At least in Java 5 and 6. The article you linked to is about an older VM.
The article is from 2003. CLI (and java VMs) have advanced a lot since then. In general you have to be very cautious whenever doing micro benchmarks. It is real easy to end up measuring jit performance, compiler efficiency at removing dead code, timing overhead, garbage collection, and so on.
Java 并不总是优化空循环的方式。在这种情况下,计算 4 个 BN 数字需要 2.966 秒。
long start = System.nanoTime();
for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++);
long time = System.nanoTime() - start;
System.out.printf("Took %.3f seconds to empty loop.%n", time * 1e-9);
印刷
Took 2.966 seconds to empty loop.
这是使用 Java 6u11,也许 6u14 会更聪明。
In general, try to write your code as simply as you can, so the JVM can make good guesses as to what you're trying to do.