is there any measurably performance difference between
((TypeA) obj).method1(); ((TypeA) obj).method2(); ((TypeA) obj).method3();
and
var A = (TypeA) obj; A.method1(); A.method2(); A.method3();
when used alot of times?
I often see something like
if (((TextBox)sender).Text.Contains('.') || ((TextBox)sender).Text.Contains(','))
and wonder if this is a waste of performance.
Advantages of Type Casting in CIt helps you in converting one data type to another data type. It helps in making the program lightweight. With this, you can take advantage of features like type representations and hierarchies.
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.
It depends. Usually those calculations take extra time, so they will have a performance impact. However, there are several factors that mitigate the actual impact of this: The compiler can optimize types in some cases to minimize conversions. Some platforms implement certain conversions in hardware.
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.
It may be measurable if it's being done billions of times with very little other work. I don't know whether the CLR will effectively cache the fact that the cast worked, so it doesn't need to do it again - if it doesn't do so now, it might do so in a later release. It might do so in the 64 bit JIT but not the 32 bit version, or vice versa - you get the idea. I doubt that it would make a significant difference in normal code though.
Personally I like the readability of the second form more though, and that's more important by far.
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