views:

433

answers:

5

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?

+1  A: 

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.

Ben Hardy
This is a question about .NET. He's not asking about the JVM but the .NET CLR.
Ash
+2  A: 

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! :-)

Eddie
A: 

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.

Craig P. Motlin
The OP seems to be asking about the C# JIT, however, and not Java JIT.
Eddie
A: 

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.

hacken
A: 

Java doesn't always optimise way empty loops. In this case it took 2.966 seconds to count 4 BN numbers.

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);

Prints

Took 2.966 seconds to empty loop.

This was using Java 6u11, perhaps 6u14 will be smarter.

Peter Lawrey
You probably have to use the -server VM and not the (default) -client VM to get the more advanced optimizations such as this one.
Eddie