Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of TypeCasting

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.

like image 792
sloth Avatar asked Jul 22 '09 14:07

sloth


People also ask

What are the advantages of type casting?

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.

Is type casting costly?

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.

Are type conversions slow?

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.

Is type casting expensive Java?

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.


1 Answers

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.

like image 121
Jon Skeet Avatar answered Sep 21 '22 20:09

Jon Skeet