Why defining class as final improves JVM performance?

后端 未结 5 1602
情书的邮戳
情书的邮戳 2020-11-29 01:41

Quoting from http://sites.google.com/site/gson/gson-design-document:

Why are most classes in Gson marked as final?

While Gson provides a

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 02:01

    An old, apparently no longer but still largely relevant, article on this from IBM developerWorks, which states:

    The common perception is that declaring classes or methods final makes it easier for the compiler to inline method calls, but this perception is incorrect (or at the very least, greatly overstated).

    final classes and methods can be a significant inconvenience when programming -- they limit your options for reusing existing code and extending the functionality of existing classes. While sometimes a class is made final for a good reason, such as to enforce immutability, the benefits of using final should outweigh the inconvenience. Performance enhancement is almost always a bad reason to compromise good object-oriented design principles, and when the performance enhancement is small or nonexistent, this is a bad trade-off indeed.

    Also see this related answer on another question. There's also the equivalent question for .Net, discussed here. SO discussion, "Are final methods inlined?" On a question titled "What optimizations are going to be useless tomorrow," this one appears on the list.

    Here is someone trying to characterize the effect on HotSpot inlining from static and final classes.

    Note also that there is an entangling of the effects of final classes vs. final methods. You may get some performance benefit (again, I don't have a good reference) for final methods for sure, as it could cue the JIT to do inlining it couldn't otherwise do (or not so simply). You get the same effect when you mark the class final, which means that all the methods are suddenly final as well. Note that the Sun/Oracle folks claim that HotSpot can usually do this with or without the final keyword. Are there any additional effects from having the class itself final?

    For reference, links to the JLS on final methods and final classes.

提交回复
热议问题