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

前端 未结 3 1902
眼角桃花
眼角桃花 2021-01-21 03:11

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

相关标签:
3条回答
  • 2021-01-21 03:19

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

    0 讨论(0)
  • 2021-01-21 03:34

    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.

    0 讨论(0)
  • 2021-01-21 03:34

    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 讨论(0)
提交回复
热议问题