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 javac or Hotspot automatically do this for me when it's obvious the variable cannot change. eg will javac make 'x' final in this class below...
public class MyClass {
private String x;
MyClass(String x) {
this.x = x;
}
public String getX() {
return x;
}
}
On a secondary point, has anyone produced empirical evidence that marking members as final makes code run faster? Any benefit is surely negligible in any application making remote calls or database lookups?
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.
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
AFAIK, they do not, and thus, you suffer minor penalty. This, however, can be done automatically with IDE tools like Eclipse "Cleanup" feauture.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With