Performance penalty for working with interfaces in C++?

前端 未结 16 1813
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 11:21

Is there a runtime performance penalty when using interfaces (abstract base classes) in C++?

16条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 11:53

    Another alternative that is applicable in some cases is compile-time polymorphism with templates. It is useful, for example, when you want to make an implementation choice at the beginning of the program, and then use it for the duration of the execution. An example with runtime polymorphism

    class AbstractAlgo
    {
        virtual int func();
    };
    
    class Algo1 : public AbstractAlgo
    {
        virtual int func();
    };
    
    class Algo2 : public AbstractAlgo
    {
        virtual int func();
    };
    
    void compute(AbstractAlgo* algo)
    {
          // Use algo many times, paying virtual function cost each time
    
    }   
    
    int main()
    {
        int which;
         AbstractAlgo* algo;
    
        // read which from config file
        if (which == 1)
           algo = new Algo1();
        else
           algo = new Algo2();
        compute(algo);
    }
    

    The same using compile time polymorphism

    class Algo1
    {
        int func();
    };
    
    class Algo2
    {
        int func();
    };
    
    
    template  void compute()
    {
        ALGO algo;
          // Use algo many times.  No virtual function cost, and func() may be inlined.
    }   
    
    int main()
    {
        int which;
        // read which from config file
        if (which == 1)
           compute();
        else
           compute();
    }
    

提交回复
热议问题