Should I declare a java field 'final' when if it's not modified in code?

前端 未结 7 2022
终归单人心
终归单人心 2020-12-15 21:06

My question is mainly about performance. The compiler knows better that, for example, some variable is NOT modified after object instantiation. So, why bother with final?

7条回答
  •  独厮守ぢ
    2020-12-15 21:29

    If the field is anything but private, a JVM will always have to be prepared that a class that it has not encountered yet will at some time be loaded and start modifying it. So for those fields it is possible that explicitly declaring them final will allow stronger optimizations in a JIT. This could even be true for private fields if the JIT is looking at a single method at a time.

    On the other hand, final on local variables does not survive bytecode compilation and so should have no performance effects.

提交回复
热议问题