Using the final method

I know that one of the uses of the final keyword in a method is to force subclasses to use the same method implementation. But what does it mean to say that it improves efficiency by allowing the compiler to turn method calls into embedded Java code? I just read this, but don't quite understand the idea.

In this sense, I do not understand the meaning of Java embedded code. How is the final method called? Is there anything special that Java notifies or does during compilation of code that calls the final method?

+4
source share
2 answers

Bytecodes are not significantly more or less efficient if you use final, because Java bytecode compilers usually have little to do with optimization. The performance bonus (if any) will be in the native code generated by the JIT compiler.

Theoretically, using final gives a hint to the JIT compiler, which should help it optimize. In practice, the latest HotSpot JIT compilers can do a better job ignoring your hints. For example, a modern JIT compiler typically does a global analysis to find out if a given method call is a leaf method in the context of the classes currently loading. This analysis is more accurate than your final hints can be, and the runtime may even detect when a new class is loading, which invalidates the analysis ... and repeats the analysis and generation of native code for the affected code.

Therefore, it is best practice to use the final (in the broad sense) expression of your design intentions and achieve other necessary semantic effects. (For example, using the final modifier can play an important role in implementing thread-safe types of immutable types.) If you use final as an optimization hint, you will not achieve significant results, and you will make your code more difficult to modify and extend.

font: link

+5
source

When you want to know how the Java compiler handles different constructs, one good way to find out is to use javap to disassemble the class file.

Final methods may offer an opportunity for optimization, since the code to be run is known at compile time. Otherwise, a run-time search must be performed to determine which version (original or overridden) to run.

This is a theory ... in practice, existing Java compilers do not do very aggressive optimizations.

+1
source

Source: https://habr.com/ru/post/1498619/


All Articles