c# - Does compiler optimizes unnecessary/redundant upcast away or Does it produce any IL at all? -


from do redundant casts optimized? can see compiler doesn't optimizes unnecessary downcast (i.e. castclass) away. interested in simpler case, " if compiler optimizes unnecessary upcast away?" question concerns reference type, not boxing.

it seems upcast doesn't produce il, , hence redundant explicit upcast doesn't cost @ all? or because il instruction typeless, there still performance cost redundant explicit upcast behind scene?

or upcast produce 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 foo, , implicit object     var y = new bar();           // implicit 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 

first, micro-optimization. should worry making code correct , readable. when identify parts don't perform optimize , measure whether optimizations helped.

second, if il contained castclass instruction, still optimized away in jited assembly code, wouldn't have effect on performance.

third, can't think of case upcast require castclass (or other instruction). that's because in il, methods called directly metadata token, there no need upcast right overload of method, or that. , il doesn't have type inference, need specify type parameters explicitly in case, means castclass not needed here either.


Comments