Cost of type Casting
-
Hello, Can someone give me some explanations how C++ actually doing the type casting? Is a Dynamic Cast really expensive? What about Static Cast, Constant Cast and Interrupter Cast? Thanks! Nachi
-
Hello, Can someone give me some explanations how C++ actually doing the type casting? Is a Dynamic Cast really expensive? What about Static Cast, Constant Cast and Interrupter Cast? Thanks! Nachi
The authoratative source on all things performance in C++ is: C++ Standards Committee Performance TR[^] From the performance TR: const_cast<Type>(expression) // §IS-5.2.11 static_cast<Type>(expression) // §IS-5.2.9 reinterpret_cast<Type>(expression) // §IS-5.2.10 dynamic_cast<Type>(expression) // §IS-5.2.7 The first three forms of type conversion operator have no size or speed penalty versus the equivalent cast notation. Indeed, it is typical for a compiler to transform cast notation into one of the other type conversion operators when generating object code. However, dynamic_cast may incur some overhead at run-time if the required conversion involves using RTTI mechanisms such as cross-casting (§2.3.8). The report goes on to give examples of how dynamic cast costs are dependant on the types you are casting to and from. If you believe casting to be an issue profile your application and compare the cost of the cast to the rest of the application. Casting is not likely to be significant performance cost in the bigger picture unless you do it very often - in which case the design may require refactoring. There are however, two conflicting opinions on the use of dynamic casts. One is that it is best to avoid dynamic casting where possible through the use of the visitor pattern (Design Patterns - Gamma, Helm et al.), and the other is that the use of dynamic_casts elminates the need for large ammounts of code that the visitor pattern requires. Nish's Excellant article on Casting Basics[^]
If you can keep you head when all about you Are losing theirs and blaming it on you; If you can dream - and not make dreams your master; If you can think - and not make thoughts your aim; Yours is the Earth and everything that's in it. Rudyard Kipling