In Java, is there any performance benefit gained from making local variables final?
-
I've heard contradicting views whether there can be any performance gained by making local variables final in Java. Or by creating a final local variable that references a member variable. Can anyone provide a clear answer to this? (assuming Java 6/7 and a standard JVM such as Oracle's).
-
Answer:
Accessing a local variable is faster than accessing a field. It's best to keep field accesses out of performance-critical inner loops when possible. (Profile first, of course, to see if it matters.) In theory the JVM could "inline" the field to a local variable automatically under the right conditions, but don't count on it. A final local variable is not any different from a normal local variable at runtime. The "final" keyword on a local variable expresses a constraint on the source code (that it is assigned to once) which the compiler can easily check. Final *fields* do allow additional optimizations, and static final fields with primitive values (as in "public static final int MY_CONSTANT = 3") are treated as compile-time constants and inlined.
David Greenspan at Quora Visit the source
Related Q & A:
- What do we call the "middle" variables in a complex research model?Best solution by Cognitive Sciences
- How to change variables elegantly?Best solution by Stack Overflow
- How to Implement Gateway Service something similar to Oracle API gateway Using Java and Java based Open Source frameworks only?Best solution by Quora
- Do consumers do more research before making an expensive purchase than before making a cheaper purchase?Best solution by answers.yahoo.com
- Difference between Java 2 and Java 6?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.