楼主:
iterator (rotareti)
2015-12-01 01:17:35Type casting impact over execution performance in C#
http://tinyurl.com/clr68dj
这是篇 2004 年的文章, 也就是 .NET Framework 1.1 时代,
作者的程式以及测试数据, 显示 as 比起 cast 要来得快.
但, 我们也可以看到文章下方的留言, 2006 年有人指出在 .NET 2.0 上,
可能因为微软实作及最佳化不同, 所以 cast 又比 as 快.
而后续也有数个留言提到这篇文章的结论有误.
那在 .NET Framework 到了 4.6 的 2015 年, 又是什么状况呢?
测试平台: Windows 10 TH2 x64, Visual Studio 2015
先说总结: as 快于 cast . (*1)
方式 时间
as 3,231ms
down as 3,244ms
as + object 3,251ms
down as + object 3,229ms
cast 3,246ms
down cast 4,341ms
cast + object 6,485ms
down cast + object 4,310ms
测试用的 method, 只列出两个例子:
static void MethodCastObject(object c)
{
for (int i = 0; i < int.MaxValue; i++)
{
Parent p = (Parent)c;
p.DoSomething();
}
}
static void MethodAsDown(Parent p)
{
for (int i = 0; i < int.MaxValue; i++)
{
Child c = p as Child;
c.DoSomething();
}
}
*1, 但若要说 cast 快于 as, 也并不是完全不对. 理由是: ......
楼主: iterator (rotareti) 2015-12-01 14:29:00
两者用不同的MSIL opcode, as: isinst, cast: castclass楼上这种写法, 对 compiler 来说是没什么差别的.
楼主: iterator (rotareti) 2015-12-01 20:34:00
如果讨论这种问题时,还要先讲选择 Release mode,或是选择Start Without Debugging,就有点令人莞尔了..要说 .NET 4 之后大幅优化 x64 的 as, 却没让 x86 受惠,这论述有问题,而且跟实际状况是有矛盾的.to jizang, 原文没这样写吧.