I just read again on a Java Tips site (one that I'm not going to direct traffic to by giving you a URL) the performance advice backed up by a reasonable sounding explanation. The advice is; declaring methods to be final improves performance by allowing the compiler to inline the method. Before you go off littering your code with the final keyword expecting a whooping gain in performance you'd best consider this.
The brief explination is that final is a clue to the compiler that there will be no other implementations. If there are no other implementations then the compiler can inline the method into the calling method thus eliminating the virtual method call. If variables have been declared final, the compiler can also inline those values directly into the code.
What the advice ignores is that the optimizing compiler aggressively inlines method calls. The decision to inline is based on information gathered from the run time, not by the presence of the keyword final. The compiler not only aggressively inlines the monomorphic case pointed out in the tip, it also is able to produce code for the inlining of bimorphic and trimorpic calls.
The real hurt that comes with this bogus tip is when you decide that you want to extend or override something that has been declared final. You won't be able to! So while there are some good reasons to use 'final', promoting method inlining isn't one of them.
Hi Kirk. Excellent post - I am bummed to hear that there are resources out
there that *still* offer that advice. This article by Brian Goetz:
http://www.ibm.com/developerworks/java/library/j-jtp1029.html, does the
best job I have ever seen of summarizing the correct use of final, and it
was published in *2002* for cryin' out loud! HTH, Gregg
what about final params for methods? I think IntilliJ said it improve
performance. However i think that when you improve performance outside of
your database you are crazy.
Agreed. The final keyword should be a default.
By the way final does improve performance when viewed from a macro level
and not a micro level. The less inheritance the better, ;-).
I don' t know of a good performance reason to justify the use of final
anywhere. Doesn't final in a method parameter only clear up visibility
issues for inner=classes? Another case for final is non-mutability in
multi-core multi-threading. But rather than me repeating Brian's article
I'd take Greggs suggestion and just to read that ariticle. And while you're
there, go read Brian's words on GC, object pooling and oh gosh.. just go
read the whole series ;-)
Asking whether final or non-final methods are faster is a mislead question.
The essential point is that final methods can never be slower than
non-final methods. Increasing provability of your code can never hurt
performance.