tags:

views:

393

answers:

4

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.

A: 

No, it shouldn't be avoided at all costs. 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. If you're not careful, it's not too hard to introduce bugs or decrease the readability of the code if you cast things all over the place.

DrJokepu
+11  A: 

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.

LBushkin
+3  A: 

If you can use generics then it is a better solution than casting. Boxing and unboxing is an expensive operation that should be avoided if possible. The problem is sometimes it just can't be avoided.

Also the other answer here mentioned that worrying about something as boxing is very trivial compared to specific performance concerns or code maintainability. I completely agree with that.

Lukasz
A: 

Generally, the cost of casting an object on an adhoc basis is low in the grand scale of things. However, if you are repeatedly casting objects many times then that is when you should try to avoid it if you find it is a cause of a performance issue.

After all, one of the main improvements from .NET 1.1 to 2.0 was the introduction of generics - this addressed the issue of strongly typed lists of objects (e.g. ArrayList = based on object, List = typed list)

AdaTheDev