开发者

Does the usage of interfaces slow down programs? [duplicate]

开发者 https://www.devze.com 2022-12-28 09:39 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: What is the performance cost of having a virtual method in a C++ class?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What is the performance cost of having a virtual method in a C++ class?

Is it true that interfaces slow down programs? I have heard that this is the case because during running time each during each usage of an object implementing this interface the decision has to be made which class implementing the interface this object belongs to.

I am especially interested in开发者_如何学运维 an answer for C++, but also in general. And if this is true, some numbers would be helpful, too.

Thank you very much!


Yes, but not much and certainly not enough to matter if you need the flexibility that interfaces require. (Bear in mind that if you're using an interface heavily, the relevant bits of the vtables are going to end up in L1 or L2 cache and so won't nearly as much as you fear.)


Dynamic dispatch (i.e. using virtual functions) is more expensive than a direct call.

But it would have to be a unusual program for this to be the performance limiter. More likely to limit the performance are things like disk/network access, updating the UI or memory bandwidth.


Although Billy points out that this is a lot like the other post on SO, I think it's not exactly the same... mainly because of the way this question is worded.

Because Olga talks about a "decision", I almost thought that she was getting mixed up between using interfaces vs. using a derived class, and determining if the pointer to the object is of a particular class via dynamic_cast.

If you are talking about using dynamic_cast, then from what I understand (and this is not based on concrete performance numbers), you will get a pretty significant performance hit.

If you are talking about using interfaces, well, then I feel that the minor hit in doing a vtable lookup and extra call(s) is far outweighed by a better software design.


If you use the interface pattern (i.e. abstract classes in C++), then yes there will be an overhead on the virtual function calls. But if you implemented your own, non-abstract class mechanism to acheive the same thing, you would also have an overhead, probably greater than a VF call. So in reality, there is no extra overhead.


You're probably talking about virtual inheritance in C++. The performance penalty is minor if the virtual class is not used in critical code paths. Basically the overhead is the same as additional function call.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号