I always thought final keyword has no effect, performancewise, on local method variables or parameters. So, I tried to test the following code and it seems I was wrong:
private static String doStuffFinal() {
final String a = "A";
final String b = "B";
final int n = 2;
return a + b + n;
}
private static String doStuffNotFinal() {
String a = "A";
String b = "B";
int n = 2;
return a + b + n;
}
I checked the bytecode and they are not the same for these 2 methods. Decompiled code in idea looks like this:
private static String doStuffFinal() {
String a = "A";
String b = "B";
int n = 2;
return "AB2";
}
private static String doStuffNotFinal() {
String a = "A";
String b = "B";
int n = 2;
return a + b + n;
}
Why is there a difference between these 2 methods? Can't javac optimize such a trivial case? The compiler could see that a, b and n don't change in doStuffNotFinal and optimize the code in the same way. Why doesn't that happen?
More importantly, does that mean we'd better put the final keyword all over the place just to be sure to get the best optimizations?