I've heard that this is the case, but I couldn't find a definitive online source to confirm it.
Background: A colleague likes to make his local variables final
. One of his reasons for doing so is performance. My contention is that Java's HotSpot Just In Time compiler will automatically detect invariant local variables, and make them final
, so there is no performance benefit to doing that ourselves.
Note that I'm not asking whether it's good coding practice to make local variables final
, because there are already plenty of (off-topic) SO questions about that.
EDIT: mrhobo makes a good point about optimization of the bytecode for integer literals. I should have given an example of the type of code I was talking about, with my question:
Object doSomething(Foo foo) {
if (foo == null) {
return null;
}
final Bar bar = foo.getBar();
final Baz baz = this.bazMap.get(bar);
return new MyObject(bar, baz);
}
Do you think the same type of optimization happens in this scenario, because bar
and baz
are both marked final
? Or does HotSpot automatically detect that they're not changing within the scope of the method, and treat them as final
anyway?
Similar Questions
- Declaring local variable as final in a loop
- same question, but derives the answer empirically (by looking at classfiles), with no documentation reference
- Do javac or Hotspot automatically add 'final' as an optimisation of invariant variables?
- same question for instance variables
- Inlining in Java
- same question for methods
- Does use of final keyword in Java improve the performance?
- similar question, with no consensus for local variables
final int i = 1;
you will have an iconst corresponding to1
. If you writeint i = 1;
you will get the same. – Meredithmeredithe