Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cost of virtual calls with optimization

Tags:

c++

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?

like image 739
Q-bertsuit Avatar asked Oct 06 '15 12:10

Q-bertsuit


People also ask

Are virtual functions slower?

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.

Are virtual function calls slow?

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.

How do Vtables work?

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.

What is virtual void in C++?

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.


1 Answers

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.

like image 152
yngccc Avatar answered Sep 29 '22 09:09

yngccc