Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Java inline over virtual function boundaries?

Tags:

java

function

jit

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?

like image 297
Trent Avatar asked Nov 12 '09 02:11

Trent


People also ask

Can you inline a virtual function?

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.

Does Java allow virtual functions?

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.

Why are C# methods not virtual by default?

They're non-virtual by default because the language-designers had a decision to make and that's what they chose.

What is the difference between virtual functions and pure virtual functions?

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.


1 Answers

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.

like image 154
Stephen C Avatar answered Nov 14 '22 17:11

Stephen C