What are the memory/performance overheads of enabling RTTI in a C++ program?
Can anyone please throw some light between the internal implementation of RTTI mechanism and the relevant overheads?
I do understand how to use RTTI through typeid
and dynamic_cast
, what I am trying to know is the internal implementation details of how the run time keeps track of this information and how it is an overhead?
Run-time type information (RTTI) is a mechanism that allows the type of an object to be determined during program execution. RTTI was added to the C++ language because many vendors of class libraries were implementing this functionality themselves. This caused incompatibilities between libraries.
Overview. In C++, RTTI can be used to do safe typecasts, using the dynamic_cast<> operator, and to manipulate type information at runtime, using the typeid operator and std::type_info class.
Typically, RTTI is implemented by placing an additional pointer in a class s virtual function table. This pointer points to the type_info structure for that particular type.
In C++ the RTTI is a mechanism, that exposes information about an object's datatype during runtime. This feature can be available only when the class has at least one virtual function. It allows the type of an object to be determined when the program is executing. In the following example, the first code will not work.
Enabling RTTI typically brings only a small overhead. The usual implementation carries a pointer to the type information structure in the vtable of an object. Since the vtable must be constructed anyway, the extra time is small - it's like adding another virtual function to the class.
typeid
is therefore comparable to calling a virtual function.
dynamic_cast
is slower - it needs to traverse the inheritance hierarchy to do a cast. Calling dynamic_cast
too frequently can be a performance bottleneck. By 'can' I mean that it usually won't …
There is a slight bloat in executable size since the typeinfo structures need to be stored somewhere. In most cases it won't be relevant.
Please read appropriate section in this document.
To sum up:
typeid
(5.3.7): find vtable, through that find most derived class object, then extract type_info from that object's vtable. It is still very slow comparing with function call;
dynamic_cast
(5.3.8): find type_info as described above, then determine whether conversion is possible, then adjust pointers. Run-time cost depends on the relative position in the class hierarchy of two classes involved. Down- and cross-casts are very slow these days (though here you can find the article about possible (but restricted) constant-time implementation of dynamic_cast).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With