3

It seems logical to do some optimization around static final constants ( e.g. replace the variable with literals etc ) to improve the performance

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - what kind of optimization a JVM or class loader does?
@JRomio - in the case that @Jon is talking about, nothing. The work has already been don by javac.
1

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....

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.