开发者

Does java(compiler or jvm) handles static final members of class differently? If yes how

It seems logical to do some optimization around static final constants ( e.g. replace the variab开发者_如何学Cle with literals etc ) to improve the performance


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜