Why virtual function call is faster than dynamic_cast?

后端 未结 4 1555
渐次进展
渐次进展 2020-12-30 09:24

I wrote a simple example, which estimates average time of calling virtual function, using base class interface and dynamic_cast and call of non-virtual function. Here is it:

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-30 10:11

    You are just measuring the cost of dynamic_cast<>. It is implemented with RTTI, that's optional in any C++ compiler. Project + Properties, C/C++, Language, Enable Run-Time Type Info setting. Change it to No.

    You'll now get an unsubtle reminder that dynamic_cast<> can no longer do the proper job. Arbitrarily change it to static_cast<> to get drastically different results. Key point here is that if you know that an upcast is always safe then static_cast<> buys you the performance you are looking for. If you don't know for a fact that the upcast is safe then dynamic_cast<> keeps you out of trouble. It is the kind of trouble that is maddingly hard to diagnose. The common failure mode is heap corruption, you only get an immediate GPF if you are really lucky.

提交回复
热议问题