当前位置: 代码迷 >> C# >> C#里面的强制转型,不怕的自身类型,是不是也有性能开销
  详细解决方案

C#里面的强制转型,不怕的自身类型,是不是也有性能开销

热度:24   发布时间:2016-05-05 03:21:21.0
C#里面的强制转型,哪怕的自身类型,是不是也有性能开销?
例如,我自己实现IEnumerator接口的话,我的Current重载函数返回的是Object,那么使用的时候还得强制转型回string类型:

string s = "abc"
object obj=s;
string s2=obj;//我的问题是,这个语句会有类型转换时的类型检查开销吗?

thx!

------解决思路----------------------
有的,如果是值类型,需要装箱,引用类型没有开销
你可以实现IEnumerator<T>,IEnumerator的泛型版本
------解决思路----------------------
强制类型转换发生在编译时。
在运行时,无论任何情况下引用的赋值CLR都会检查类型是否相符,不存在你说的额外的开销。
------解决思路----------------------
引用:
强制类型转换发生在编译时。
在运行时,无论任何情况下引用的赋值CLR都会检查类型是否相符,不存在你说的额外的开销。

		static void Main(string[] args)
{
Stopwatch stopwatch;
string strStr = "string";
object objStr = strStr;
string strTarget;
object objTarget;
int count = int.MaxValue;

stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
strTarget = strStr;
stopwatch.Stop();
Console.WriteLine("string to string: " + stopwatch.Elapsed);

stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
strTarget = (string)objStr;
stopwatch.Stop();
Console.WriteLine("object to string: " + stopwatch.Elapsed);

stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
objTarget = strStr;
stopwatch.Stop();
Console.WriteLine("string to object: " + stopwatch.Elapsed);

stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
objTarget = objStr;
stopwatch.Stop();
Console.WriteLine("object to object: " + stopwatch.Elapsed);
}

Release下的结果:

string to string: 00:00:00.8043824
object to string: 00:00:03.9572322
string to object: 00:00:00.8029497
object to object: 00:00:00.8057540

很显然强制类型转换并不是编译时,而是运行时
------解决思路----------------------
不过这个开销很明显是非常小的,完全没必要在意
  相关解决方案