I have a question about the cost of virtual calls when the type pointed to is always the same:
class Base
{
Base() {};
virtual void Func() = 0;
};
class Derived
: public Base
{
Derived() : Base() {};
void Func() { /* Do something */ };
};
int main()
{
Base* base = new Derived;
for (int i = 0; i < 1000; ++i)
{
base->Func();
}
return 0;
}
Will the compiler optimize this virtual call away?
Virtual functions are by definition slower than their non-virtual counterparts; we wanted to measure the performance gains from inlining; using virtual functions would make the difference even more pronounced.
Virtual functions are slow when you have a cache miss looking them up. As we'll see through benchmarks, they can be very slow. They can also be very fast when used carefully — to the point where it's impossible to measure the overhead.
For every class that contains virtual functions, the compiler constructs a virtual table, a.k.a vtable. The vtable contains an entry for each virtual function accessible by the class and stores a pointer to its definition. Only the most specific function definition callable by the class is stored in the vtable.
A C++ virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword. It is used to tell the compiler to perform dynamic linkage or late binding on the function.
GCC with -O3 doesn't seem to optimize virtual call away.
https://goo.gl/TwZD6T
.L5
movq (%rdx), %rdx
cmpq Derived::Func(), %rdx
je .L3
movq %rbp, %rdi
call *%rdx
subl $1, %ebx
jne .L11
This does a function pointer comparison and if not equal goes ahead and do an indirect function call.
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