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 inline over virtual function boundaries.
Why Java Will Always Be Slower than C++ (wayback link)
What does this mean? Does it mean that the JIT can inline virtual function calls (because presumably it has access to run time information) whereas C++ must call the function through its vtable?
Whenever a virtual function is called using a base class reference or pointer it cannot be inlined because the call is resolved at runtime, but whenever called using the object (without reference or pointer) of that class, can be inlined because the compiler knows the exact class of the object at compile time.
Yes, you can write virtual "functions" in Java. Show activity on this post. In Java, all public (non-private) variables & functions are Virtual by default. Moreover variables & functions using keyword final are not virtual.
They're non-virtual by default because the language-designers had a decision to make and that's what they chose.
A virtual function is a member function of base class which can be redefined by derived class. A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract.
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.
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