Does use of final keyword in Java improve the performance?

Usually not. For virtual methods, HotSpot keeps track of whether the method has actually been overridden, and is able to perform optimizations such as inlining on the assumption that a method hasn’t been overridden – until it loads a class which overrides the method, at which point it can undo (or partially undo) those optimizations.

(Of course, this is assuming you’re using HotSpot – but it’s by far the most common JVM, so…)

To my mind you should use final based on clear design and readability rather than for performance reasons. If you want to change anything for performance reasons, you should perform appropriate measurements before bending the clearest code out of shape – that way you can decide whether any extra performance achieved is worth the poorer readability/design. (In my experience it’s almost never worth it; YMMV.)

EDIT: As final fields have been mentioned, it’s worth bringing up that they are often a good idea anyway, in terms of clear design. They also change the guaranteed behaviour in terms of cross-thread visibility: after a constructor has completed, any final fields are guaranteed to be visible in other threads immediately. This is probably the most common use of final in my experience, although as a supporter of Josh Bloch’s “design for inheritance or prohibit it” rule of thumb, I should probably use final more often for classes…

Leave a Comment