Possible Duplicate:
Perfomance of TypeCasting
How expensive is it to cast as object as a another object?
CustomClass instance = GenericObject as CustomClass
Should it be avoided as all costs?
Wanting to see how others think about this. I'm sure it's very situational.
Casting isn't very expensive. Of course, if you have a loop that runs a million times a second it might make sense to avoid casting to save some performance, otherwise it won't really cause performance issues. The real problem with casting is that it's cheating type safety.
To answer your questions. Up casting usually costs virtually nothing, (when you change the reference type to a parent class of the object). Knowledge of the reference type is enough to decide if uptyping is valid, it just gets the class loader to look up the inheritance map.
Overall, being “type-cast” is not necessarily a bad thing, in fact it helps Hollywood produce quality movies. Actors and actresses hone a craft and make a certain type of character and role theirs and it improves the movies they make.
C# includes another method of performing explicit conversions. Using the "as" operator, an object can be converted from one type to another. Unlike with explicit casting, if the conversion is not possible because the types are incompatible the operation does not throw an exception.
You should avoid worrying about the performance implications of specific language features unless you have specific evidence (measurements) that they are actually causing a problem.
Your primary concerns should be the correctness of the code and it's maintainability.
As a general observation, however, unnecessary casting can often be avoided in C# just by applying good OO programming practices and using generics (particularly the collections) appropriately. In those cases where you do need to perform casting, it's highly unlikely to be a performance bottleneck unless you're doing it in a tight loop or with types that are likely to throw an invalid cast exception.
Most real world performance problems emerge from algorithm choices or a lack of awareness of the platform itself - not from specific language features.
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