Does .NET JIT optimize empty loops away?

佐手、 提交于 2019-12-01 10:34:23

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 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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!