Why virtual function call is faster than dynamic_cast?

后端 未结 4 1554
渐次进展
渐次进展 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:17

    The difference is, that you can call the virtual function on any instance that is derived from Base. The notVirtualCall() member does not exist within Base, and cannot be called without first determining the exact dynamic type of the object.

    The consequence of this difference is, that the vtable of the base class includes a slot for virtualCall(), which contains a function pointer to the correct function to call. So, the virtual call simply chases the vtable pointer included as the first (invisible) member of all objects of type Base, loads the pointer from the slot corresponding to virtualCall(), and calls the function behind that pointer.

    When you do a dynamic_cast<>, by contrast, the class Base does not know at compile time what other classes will eventually derive from it. Consequently, it cannot include information within its vtable that eases the resolution of the dynamic_cast<>. That is the information lack that makes a dynamic_cast<> more expensive to implement than a virtual function call. The dynamic_cast<> has to actually search through the inheritance tree of the actual object to check whether the destination type of the cast is found among its bases. That is work that the virtual call avoids.

提交回复
热议问题