It seems logical to do some optimization around static final constants ( e.g. replace the variable with literals etc ) to improve the performance
Yes, javac
already does this (assuming your static final
fields are for a primitive type or String
): the constant value is "pasted in" directly at the point of use.
Of course, the downside to this is that if you change the field and forget to recompile the classes that use that field, then the value will be stale....
For inlinable constants (strings, numbers) the compiler does behave differently, yes.
When the compiler spots a constant expression, it embeds the result of that constant expression into the code that uses it, rather than computing it each time. So if you had:
public static final int FOO = 10;
public static final int BAR = 5;
...
System.out.println(FOO * BAR);
then the constant value 50 would be directly embedded in the code.
Note that this has a versioning caveat associated with it - if you change FOO
or BAR
, you need to recompile everything that refers to it as well... otherwise they'll still be using the "old" value as it will be embedded in their bytecode.
Yes, static final primitives are replaced, inline, in compiled bytecode. This can be the source of problems, since if that constant changes, all source files which need it (not just the one it is declared in) must be recompiled.