RTTI Overhead in C++
What are the memory/performance overheads of enabling RTTI in a C++ program?
Can anyone please throw some light between the开发者_C百科 internal implementation of RTTI mechanism and the relevant overheads? I do understand how to use RTTI throughtypeid
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?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).
First there is no way to say exactly how much overhead is involved with out specifying a compiler and version as it is an implementation detail. That said it is well known that in some compilers dynamic_cast searches the class hierarchy doing string comparisons to match class names.
I wonder where did get the idea of RTTI "overhead" ?
I read on the net, that in order to provide R.T.T.I., some (early) C to C++ preprocessors or translators, similar tools (GObject, QT, Objective-C, not sure), and other progr. langr. generate some "behind the scene" code, that did generate some "overhead" in memory and speed.
I read that eventually, that "overhead" was reduced and many times is considered trivial.
Maybe you would like to program in assembly, or "plain C", without R.T.T.I. overhead, is much easier than C++
精彩评论