Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Expensive is Casting an Object? [duplicate]

Tags:

c#

casting

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.

like image 843
bobber205 Avatar asked Dec 17 '09 19:12

bobber205


People also ask

Is casting expensive?

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.

Is casting in Java expensive?

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.

Is type casting bad?

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.

How do I cast one object to another in C#?

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.


1 Answers

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.

like image 71
LBushkin Avatar answered Sep 29 '22 20:09

LBushkin