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

断了今生、忘了曾经 提交于 2019-12-01 06:11:05

Like many performance "enhancements" it is usually a better to ask; What is easier to understand and reason about? e.g. if a field is final I know it won't be changed anywhere. This is often leads to more optimial code, but more importantly it should be more maintainable code. ;)

Certainly, I make any field which can be final as final. Personally I would have preferred that final be the default behaviour and you had to use a keyword like var to make it mutable.

questzen

Allowing javac to do this would be a blunder. As there might be code in a different jar which may rely on the code being compiled (modularity), changing code at compile time for optimization sake is not a feasible option.

As for the second argument "never need reloading from the main memory", one needs to remember that most instance variables are cached. final only indicates immutability, it does not guarantee volatility (volatile == always get latest from main memory). Hence the need for locks and volatile keyword in multi-threaded environment.

As for the case with hotspot, I have no clue, and would like to hear more about it. final constants may be in-lined at compile time, thus allowing moderate performance gains. Reference to a question on in-lining in java

Edit:

Note that final indicates immutability needs to be taken with a grain of salt. It does not guarantee that the state cannot change, it only specifies that the object reference can be modified. final indicates immutability for primitive data types

AFAIK, they do not, and thus, you suffer minor penalty. This, however, can be done automatically with IDE tools like Eclipse "Cleanup" feauture.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!