2

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?

Michael Liu
  • 52,147
  • 13
  • 117
  • 150
Bohn
  • 26,091
  • 61
  • 167
  • 254

1 Answers1

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