我有以下简单的值类型:
public struct MyUInt32
{
public uint m_value;
public static implicit operator MyUInt32(UInt32 uInt32)
{
return new MyUInt32(uInt32);
}
public static implicit operator UInt32(MyUInt32 myUInt32)
{
return myUInt32.m_value;
}
public MyUInt32(UInt32 uInt32)
{
m_value = uInt32;
}
}
显然是真的
System.UInt32
编译器有一些神奇的方法来处理鸡和蛋的情况,其中
uint
是的别名
UInt32
和
UInt32
包括
无符号整型
在它的定义中。
因此,我还假设编译器有一些其他技巧来优化
系统UInt32
这可以在以下比较测试中看出:
MyUInt32 myUInt32= 0;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i=1;i<int.MaxValue;i++)
{
myUInt32++;
}
stopwatch.Stop();
Console.WriteLine($"Elapsed time (implicit): {stopwatch.Elapsed}");
stopwatch.Reset();
stopwatch.Start();
for (int i = 1; i < int.MaxValue; i++)
{
myUInt32.m_value++;
}
stopwatch.Stop();
Console.WriteLine($"Elapsed time (reference): {stopwatch.Elapsed}");
UInt32 uint32 = 0;
stopwatch.Reset();
stopwatch.Start();
for (int i = 1; i < int.MaxValue; i++)
{
uint32++;
}
stopwatch.Stop();
Console.WriteLine($"Elapsed time (uint): {stopwatch.Elapsed}");
它给出了:
Elapsed time (implicit): 00:00:12.4340519
Elapsed time (reference): 00:00:03.5583824
Elapsed time (uint): 00:00:01.8550149
有没有告诉编译器进行优化
MyUInt32
所以它的表现就像
系统UInt32
?