Performance penalty for working with interfaces in C++?

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

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

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

    The only main difference I know of is that, since you're not using a concrete class, inlining is (much?) harder to do.

    0 讨论(0)
  • Most people note the runtime penalty, and rightly so.

    However, in my experience working on large projects, the benefits from clear interfaces and proper encapsulation quickly offset the gain in speed. Modular code can be swapped for an improved implementation, so the net result is a large gain.

    Your mileage may vary, and it clearly depend on the application you're developing.

    0 讨论(0)
  • 2020-12-02 12:01

    Short Answer: No.

    Long Answer: It is not the base class or the number of ancestors a class has in its hierarchy that affects it speed. The only thing is the cost of a method call.

    A non virtual method call has a cost (but can be inlined)
    A virtual method call has a slightly higher cost as you need to look up the method to call before you call it (but this is a simple table look up not a search). Since all methods on an interface are virtual by definition there is this cost.

    Unless you are writing some hyper speed sensitive application this should not be a problem. The extra clarity that you will recieve from using an interface usually makes up for any perceived speed decrease.

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

    Functions called using virtual dispatch are not inlined

    There is one kind of penalty for virtual functions which is easy to forget about: virtual calls are not inlined in a (common) situation where the type of the object is not know compile time. If your function is small and suitable for inlining, this penalty may be very significant, as you are not only adding a call overhead, but the compiler is also limited in how it can optimize the calling function (it has to assume the virtual function may have changed some registers or memory locations, it cannot propagate constant values between the caller and the callee).

    Virtual call cost depends on platform

    As for the call overhead penalty compared to a normal function call, the answer depends on your target platform. If your are targeting a PC with x86/x64 CPU, the penalty for calling a virtual function is very small, as modern x86/x64 CPU can perform branch prediction on indirect calls. However, if you are targeting a PowerPC or some other RISC platform, the virtual call penalty may be quite significant, because indirect calls are never predicted on some platforms (Cf. PC/Xbox 360 Cross Platform Development Best Practices).

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