简体   繁体   中英

c++ virtual function performance

I have two classes foo and bar where one is a superclass of the other, and they both have a method hello_world .

class foo {
    virtual void hello_world();
};
class bar : public foo {
    void hello_world();
};

My question is: is there any performance difference if I make it virtual for bar 's hello_world ? It will become this:

class foo {
    virtual void hello_world();
};
class bar : public foo {
    virtual void hello_world();
};

I will mainly call hello_world from bar . I know virtual function will make functions slow because we do run time look up. But for this case, is there any difference?

Calling a virtual function in a context where the class may, indeed, be polymorphic always has some performance impact compared to a function with the same logic that can be inlined. The primary reasons are that there is a small overhead calling a function, a small overhead in looking up which function needs to be called, and a major loss of optimization opportunities. The last point is typically the most expensive one.

The original example didn't compile, ie, it is pretty clear that no performance analysis was done, yet. Worry about the performance impact once you have measured that your code runs too slow and that the specific call is, indeed, in the area where the performance problem comes from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM