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

前端 未结 7 2040
终归单人心
终归单人心 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:26

    For local variables the final modifier is not kept in the bytecode, so there can be no performance difference. For a field member the performance implications are more complicated. It might give the jit a hint that the field is not modified and allow it to cache the value in a register. On the other hand, final does give some guarantees regarding the visibility of the fields value to other threads, which might actually slow down object construction.

    Performance wise I think this is a micro optimisation whose effect would be hardly measurable.

    I would still recommend to use final when possible to clarify your intent to to your colleagues and your future self.

提交回复
热议问题