Does Java have global variables?

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

Was this solution helpful to you?

Find solution

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.