How can Java inline over virtual function boundaries?

前端 未结 3 887
轮回少年
轮回少年 2021-02-20 10:03

I\'m reading up some material on whether Java can be faster than C++, and came across the following quote:

Java can be faster than C++ because JITs can in

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-20 10:54

    The answer to your question is Yes: that is what the quoted text means.

    The JIT will analyse all of the loaded classes. If it can determine that there is only one possible method that can be called at any given point, it can avoid the dispatching and (if appropriate) inline the method body.

    By contrast, a C++ compiler does not know all of the possible subtypes, and therefore cannot determine if this optimization can be done for a (virtual) method. (And by the time the linker runs, it is too late ...)

    Other answers have said that you can do this optimization by hand in C++ ... but that assumes that you (the programmer) can do the analysis yourself, and change methods from virtual to non-virtual. But if you get it wrong, you've got a bug to track down.

    By the way, we can assume that this optimization is worthwhile for the average Java application. If it was not, the JIT compiler guys would not have implement it. After all, a worthless optimization is only going to make Java applications start more slowly.

提交回复
热议问题