Performance penalty for working with interfaces in C++?

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

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

相关标签:
16条回答
  • 2020-12-02 11:37

    When you call a virtual function (say through an interface) the program has to do a look up of the function in a table to see which function to call for that object. This gives a small penalty compared to a direct call to the function.

    Also, when you use a virtual function the compiler cannot inline the function call. Therefore there could be a penalty to using a virtual function for some small functions. This is generally the biggest performance "hit" you are likely to see. This really only an issue if the function is small and called many times, say from within a loop.

    0 讨论(0)
  • 2020-12-02 11:37

    Using abstract base classes in C++ generally mandates the use of a virtual function table, all your interface calls are going to be looked up through that table. The cost is tiny compared to a raw function call, so be sure that you need to be going faster than that before worrying about it.

    0 讨论(0)
  • 2020-12-02 11:41

    I don't think that the cost comparison is between virtual function call and a straight function call. If you are thinking about using a abstract base class (interface), then you have a situation where you want to perform one of several actions based of the dynamic type of an object. You have to make that choice somehow. One option is to use virtual functions. Another is a switch on the type of the object, either through RTTI (potentially expensive), or adding a type() method to the base class (potentially increasing memory use of each object). So the cost of the virtual function call should be compared to the cost of the alternative, not to the cost of doing nothing.

    0 讨论(0)
  • 2020-12-02 11:42

    The only thing I can think of is that virtual methods are a little bit slower to call than non-virtual methods, because the call has to go through the virtual method table.

    However, this is a bad reason to screw up your design. If you need more performance, use a faster server.

    0 讨论(0)
  • Yes, but nothing noteworthy to my knowledge. The performance hit is because of 'indirection' you have in each method call.

    However, it really depends on the compiler you're using since some compilers are not able to inline the method calls within the classes inheriting from the abstract base class.

    If you want to be sure you should run your own tests.

    0 讨论(0)
  • 2020-12-02 11:44

    Yes, there is a penalty. Something which may improve performance on your platform is to use a non-abstract class with no virtual functions. Then use a member function pointer to your non-virtual function.

    0 讨论(0)
提交回复
热议问题