從Do redundant casts get optimized?我可以看到,編譯器不會優化不必要的向下轉換(即castclass
)。但是現在我對一個更簡單的情況感興趣,「如果編譯器優化了不必要的拋棄?」這個問題只涉及參考類型,而不是boxing
。編譯器是否優化了不必要的/冗餘的丟棄或者它是否產生任何IL?
在我看來,upcast
不會產生任何IL,因此多餘的顯式upcast
完全沒有成本?或者因爲IL指令是無類型的,幕後的冗餘顯式upcast
仍有性能成本?
或者有時會上傳產生任何IL指令?
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
它可能是c#編譯器刪除演員到'Foo',導致它是不必要的 – Jehof
@Jehof是的,這就是我想問的問題:C#總是優化掉不必要的上傳嗎? – colinfang
當然,這是一個非常簡單的優化實施。 IL是非*無類型的,遠非如此。 –