c++ - 从多态基指针调用基类方法很慢

标签 c++ class oop c++11 polymorphism

标题很困惑..这是一个总结它的最小代码 -

#include <iostream>
#include <chrono>
#include <memory>

using namespace std;
using namespace std::chrono;

enum class TYPE {base, child};

class Base {
    int n;
  protected: Base(int _n) : n(_n) {}
  public: virtual TYPE getType(){ return TYPE::base; }
};

class Child: public Base {
    int m;
  public:
    TYPE getType(){ return TYPE::child; }
    Child(int _n, int _m) : Base(_n), m(_m) {}
};

int main() {
    unique_ptr<Base> b = make_unique<Child>(6, 7);
    TYPE tB = TYPE::base;
    TYPE tC = TYPE::child;

    {
        auto t1 = high_resolution_clock::now();

        std::cout << (tB == b->Base::getType()) << ", ";

        auto t2 = high_resolution_clock::now();
        auto duration = duration_cast<microseconds>( t2 - t1 ).count();
        cout << "Duration: " << duration << std::endl;

    }

    {
        auto t1 = high_resolution_clock::now();

        std::cout << (tC == b->getType()) << ", ";

        auto t2 = high_resolution_clock::now();
        auto duration = duration_cast<microseconds>( t2 - t1 ).count();
        cout << "Duration: " << duration << std::endl;

    }

    return 0;
}

输出如下-

1, Duration: 12  // first run was 62
1, Duration: 0

我理解虚函数与普通(编译时间解析)函数相比可能会慢一点,但为什么上面的函数 - b->Base::getType() 比虚函数慢方法 - b->getType()?它是否进行了两次旅行,例如虚拟地解析函数然后返回到基类?谁能帮助我理解这一点?

IDEONE


嗯,稍微修改代码以包含循环,结果很清楚 - <强> IDEONE

1, Duration: 33
1, Duration: 1478051

最佳答案

调用 cout 所用的时间超过了单个函数调用的计时数字。最初的 cout 调用可能会为缓冲区分配内存,并且会花费更长的时间。

第一个调用 (b->Base::getType()) 不是虚拟的,甚至可以是内联的。

关于c++ - 从多态基指针调用基类方法很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39652321/

相关文章:

c++ - 在完成端口调用 WSASend()?

c++ - C++ 中的 C 库

python - 在实例方法中更新类变量

mysql - com.mysql.jdbc.Driver 找不到类异常

C# 多级对象和列表访问

c++ - 终止 DebugActiveProcess 或其他调试例程

c++ - 在 xcode 的 ios 项目中实现 C++ bitvector

类中的 C++ 对象构造

java - OOD - 将配置传递给外部类的最佳方法

C++ 从基类继承构造函数