I know that boxing/unboxing affects performance. According to MSDN, unboxing can take four times as long as an assignment. We have many lines in our code that have "redundant" casts. They are not actually needed and the code compiles fine without them. Probably it won't hurt performance because the compiler sees that there is no need to do the unboxing, but maybe not! Maybe when we cast them explicity the compiler will be forced to do an unnecessary unboxing. I'm wondering if that type of "redundant casting" also affects performance just like unboxing or nop?
Asked
Active
Viewed 964 times
2
-
2Can you please post some sample of what you are talking about ? – Angshuman Agarwal May 26 '12 at 15:24
-
1You might look here http://stackoverflow.com/questions/5278674/do-redundant-casts-get-optimized for more discussion. – Asya Kamsky May 26 '12 at 15:40
1 Answers
6
Truly redundant casts like (int)0
or (object)null
are elided by the compiler. Because the generated IL is exactly the same whether or not you use a cast expression, there is no performance penalty. The same goes for an explicit cast where a boxing conversion would be performed anyway:
object value = 0;
object value = (object)0; // exactly the same

Michael Liu
- 52,147
- 13
- 117
- 150