Are Java final methods automatically inlined?
Many books says yes many books says no!!!
If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as final, we restrict the other classes to inherit or extend it. In other words, the final classes can not be inherited by other classes.
Can We Override a Final Method? No, the Methods that are declared as final cannot be Overridden or hidden.
What Method Inlining Is? Basically, inlining is a way to optimize compiled source code at runtime by replacing the invocations of the most often executed methods with its bodies. Although there's compilation involved, it's not performed by the traditional javac compiler, but by the JVM itself.
No, Java does not provide inline functions it is typically done by the JVM at execution time.
Inlining of methods is performed by the JIT compiler, not javac.
Modern JIT compilers (including Hotspot) can often inline even non-final methods, "undoing" the optimisation appropriately if necessary. They're basically scarily clever.
In short: it entirely depends on the VM. In my opinion, you should make your methods final or not based on what produces the cleanest code rather than performance. I'm personally a fan of "design for inheritance or prohibit it" but that's a different discussion :)
Interesting question, prompted me to look into it further. 2 interesting remarks I found -
Contrary to the implication of many tips, methods declared as final cannot be safely inlined by the compiler, because the method could have a non-final declaration at runtime.
To see why, suppose the compiler looks at class A and subclass B, and sub-subclass C and sees a final method in A which it inlines into C. But then at runtime the versions loaded for A and B are different and the method is not final in A, and overridden in B. Then C uses the incorrectly inlined version. T
And, a bit more authoritatively, from a sun whitepaper, writing that methods can be left virtual,
Because the Java HotSpot VM can automatically inline the vast majority of virtual method invocations, this performance penalty is dramatically reduced, and in many cases, eliminated altogether.
Here's a more direct reference on the mechanism.
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