In Java, is there any performance benefit gained from making local variables final?

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.

Answer by David Greenspan:

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.

In Java, is there any performance benefit gained from making local variables final?

Advertisements

Leave a comment

Filed under Life

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s