Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method calls faster than virtual method calls in C++?

Just stumbled upon this in wikipedia:

Java can access derived instance methods faster than C++ can access derived virtual methods due to C++'s extra Virtual-Table look-up. However, non-virtual methods in C++ do not suffer from V-Table performance bottlenecks, and thus exhibit performance similar to that of Java.

Is this correct? As far as I know, ALL calls are virtual in Java, and still rely on a virtual table, so my common logic suggests that Java calls cannot possibly be faster than virtual C++ calls.

Am I misinformed or is the article wrong? At any rate - is there a FASTER way of resolving calls at runtime than a virtual table?

like image 528
dtech Avatar asked Dec 27 '22 09:12

dtech


1 Answers

It might have to do with optimizations performed by the JIT compilation. In some cases I could imagine the JVM to detect that a certain (virtual) call always refers to a certain implementation and the lookup is not needed.

OTOH, a C++ compiler might also be able to deduce that a lookup is not required in some cases and produce equally good code. Also, virtual functions are not required by C++, so there is the an alternative that Java does not offer.

That said, if you need the functionality that virtual offers in C++, there is no generally better alternative I could think of. If you care about performance, just be aware that virtual usually does have a cost and that it should only be used where needed.

In general, I find statements like the one you quoted unhelpful and misleading (not your fault, of course).

like image 157
Daniel Frey Avatar answered Jan 09 '23 19:01

Daniel Frey