Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ virtual function execution efficiency

I am trying to get a better idea of performance of virtual functions here is an example code:

struct Foo {
    virtual void function1();
    virtual void function2() { function1(); }
};

struct Bar : Foo {
    virtual void function1();
}

Bar b;
Foo &f = b;

b.function2();
b.function1();
f.function2();

for each of three calls in the last three lines of the code sample, do all of them have to look up function pointer in virtual table? how many lookup have to be done for f object. which once can be inlined by compiler?

thanks

like image 878
Anycorn Avatar asked Dec 18 '22 03:12

Anycorn


1 Answers

The calls on b are static - the compiler knows for sure at compilation time what the type of b will be at runtime (obviously a Bar) so it will directly use the addresses of the methods that will be invoked.

Virtual only matters when you make a call via pointer/reference as the call could have different targets at runtime. This would matter if, for example, you called function1 on a pointer and during runtime changed the actual type that the pointer pointed to.

Now the situation here, where you call function2 on f is tricky for two reasons: the function is never overridden, and you use a reference which cannot be reassigned. Therefore, a really smart compiler that sees all input files could conceivably figure out what the target of the call really will be with 100% confidence (since you're not going to add new classes to the already compiled code). However, AFAIK, the compilers does not have to do it so you would pay the cost.

Generally speaking, if you don't plan to override a function ever, don't make it virtual.

like image 85
Uri Avatar answered Jan 06 '23 07:01

Uri