Question

I am using the following line of code over and over in a loop:

Object val;
while (logic())
   val = val == null ? generateObj() : val;

I am curious how the JVM optimizes this code, if at all? I.e., if val != null will the JVM sense that the assignment goes back to self and just ignore the rest of the line, or will it take the time to copy the reference of val back over itself?

I am running the standard JRE 6 and JRE 7 in my environments for Windows 7.

ASIDE: If the JVM does not optimize this operation very well, what is the best alternative to doing this call? Just if (val == null) val = generateObj();?

Était-ce utile?

La solution

Curious? Pick some JVM (list of them is available here: http://en.wikipedia.org/wiki/Java_Virtual_Machine) with source code open and go debug output of the JIT compiler.

I don't know if internals of the Oracle JVM in particular (the one you're probably running on Windows) went open source, but perhaps their engineers might answer your question clearly, especially if you file in a performance-problem ticket (I used to solve this kind of tickets for Symbian JVM (there 2 of them) and we had tools to diagnose this kind stuff in detail).

In general the question how modern Java optimizes something does not have general simple answer. IMHO best way to learn more is to go pick one and play with it (run benchmarks, study traces etc.)

If you're asking how to write better code then this - super cool Stack Overflow answer - can give you some hints

EDIT: Is there a guide to setting up the JDK to compile your java code from a C Compiler? (Ideally an eclipse set up)

Yes there should be one. Just be warned that working with larger software repositories (thousands of files and hundreds of thousands up to milions of lines of code) is usually not for the faint-hearted and to get the environment setup right (even with some documentation) can take some days.

Wikipedia - List of Java virtual machines lists some open source JVMs. The Oracle JVM page points to OpenJDK - the The HotSpot Group where you can find some (lots of) resources and guides, but mainly invaluable contacts to developers who should be able to help you get up and running.

(I can not provide you with more precise instructions as I'm out of the JVM and Symbian OS business for nearly 5 years and things had changed a bit...)

Autres conseils

Java is an interpreted language. Java mainly optimizes at runtime. The generated bytecode is in general completely unoptimized. Only when the JVM executes the bytecode it will start optimizing, depending on how your code will be executed. So it might be that the JVM does not optimize anything if your loop just runs a couple of times. You can never definitely say whether the JVM will optimize something or not. It will also depend on the concrete JVM implementation. So you should never rely on that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top