0

From Do redundant casts get optimized? I can see compiler doesn't optimizes unnecessary downcast (i.e. castclass) away. But now I am interested in a simpler case, " if compiler optimizes unnecessary upcast away?" This question only concerns reference type, not boxing.

It seems to my that upcast doesn't produce any IL, and hence redundant explicit upcast doesn't cost at all? Or because IL instruction is typeless, there is still performance cost for redundant explicit upcast behind the scene?

Or would upcast produce any IL instructions sometimes?

class Foo
{
}
class Bar : Foo
{
}
bool Test(object x)
{
    return x == null;
}
void Main()
{
    var x = new Bar();
    Console.Write(Test((Foo)x)); // redundant explicit to Foo, and then implicit to Object
    var y = new Bar();           // implicit to Object
    Console.Write(Test(y));
}

IL_0000:  newobj      UserQuery+Bar..ctor
IL_0005:  stloc.0     // x
IL_0006:  ldarg.0     
IL_0007:  ldloc.0     // x
IL_0008:  call        UserQuery.Test
IL_000D:  call        System.Console.Write
IL_0012:  newobj      UserQuery+Bar..ctor
IL_0017:  stloc.1     // y
IL_0018:  ldarg.0     
IL_0019:  ldloc.1     // y
IL_001A:  call        UserQuery.Test
IL_001F:  call        System.Console.Write
Community
  • 1
  • 1
colinfang
  • 20,909
  • 19
  • 90
  • 173

1 Answers1

1

First, this is very much a micro-optimization. You should worry about making your code correct and readable. Only when you identify parts that don't perform well optimize those and measure whether your optimizations actually helped.

Second, even if the IL contained a castclass instruction, it could still be optimized away in the JITed assembly code, so it wouldn't have any effect on performance.

Third, I can't think of any case where an upcast would require castclass (or any other instruction). That's because in IL, methods are called directly by their metadata token, so there is no need to upcast to get the right overload of a method, or something like that. And IL doesn't have type inference, so you need to specify type parameters explicitly in any case, which means castclass is not needed here either.

svick
  • 236,525
  • 50
  • 385
  • 514