Why defining class as final improves JVM performance?

后端 未结 5 1604
情书的邮戳
情书的邮戳 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条回答
  •  甜味超标
    2020-11-29 02:12

    Marking classes as final allows further optimizations to be applied during the JIT stage.

    If you are calling a virtual method on a non-final class, you don't know whether the proper implementation is the one defined in that class, or some sub-class that you don't know about.

    However, if you have a reference to a final class, you know the specific implementation that is required.

    Consider:

    A extends B
    B extends C
    
    B myInstance = null;
    if(someCondition)
       myInstance = new B();
    else
       myInstance = new C();
    myInstance.toString();
    

    In this case, the JIT can't know whether C's implementation of toString() or B's implementation of toString() will be called. However, if B is marked as final, it is impossible for any implementation other than B's to be the proper implementation

提交回复
热议问题