Declare Constants Final
Declare Constants Final
Consider the following declaration at the top of a class:
static int intVal = 42; static String strVal = "Hello, world!";
The compiler generates a class initializer method, called
<clinit>
, that is executed when the class is first used. The method stores the value 42 intointVal
, and extracts a reference from the classfile string constant table for strVal
. When these values are referenced later on, they are accessed with field lookups.
We can improve matters with the "final" keyword:
static final int intVal = 42; static final String strVal = "Hello, world!";
The class no longer requires a
<clinit>
method, because the constants go into classfile static field initializers, which are handled directly by the VM. Code accessing intVal
will use the integer value 42 directly, and accesses to strVal
will use a relatively inexpensive "string constant" instruction instead of a field lookup.
Declaring a method or class "final" does not confer any immediate performance benefits, but it does allow certain optimizations. For example, if the compiler knows that a "getter" method can't be overridden by a sub-class, it can inline the method call.
You can also declare local variables final. However, this has no definitive performance benefits. For local variables, only use "final" if it makes the codeclearer (or you have to, e.g. for use in an anonymous inner class).
Comments
Post a Comment
Please post comments here:-)