Do javac or Hotspot automatically add 'final' as an optimisation of invariant variables?

后端 未结 4 1996
北荒
北荒 2021-01-13 11:40

The consensus seems to be that there is a performance benefit to marking member variables as final because they never need reloading from main memory. My question is, do jav

4条回答
  •  无人及你
    2021-01-13 12:39

    I believe a modern JVM (the Hotspot compiler) does detect that the value doesn't change, so there is no performance benefit in making parameters or variables final yourself. (If this is wrong, please provide a link or test case.) There is one exception: constants (static final).

    However, this may be different with final methods and classes. It may improve performance in this case (I'm not completely sure in what cases). By the way, what does improve performance a little bit is making functions static (if possible).

    The problem I have with final is that it clutters the code. It would be nice if final would be the default.

提交回复
热议问题