简体   繁体   English

C ++虚拟函数性能

[英]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 . 我有两个类foobar ,其中一个是另一个的超类,并且它们都有一个方法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 ? 我的问题是:如果将它虚拟hello_world barhello_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 . 我主要从bar呼叫hello_world 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. 一旦测量到代码运行太慢并且特定的调用确实在性能问题产生的区域,就不必担心性能影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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