代码之家  ›  专栏  ›  技术社区  ›  Rowan Smith

优化值类型(如System)。UInt32()

  •  0
  • Rowan Smith  · 技术社区  · 3 年前

    我有以下简单的值类型:

        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 ?

    1 回复  |  直到 3 年前
        1
  •  0
  •   Rowan Smith    3 年前

    多亏了CharlieFace,答案只是在RELEASE中编译,而不是在DEBUG中编译。

    Elapsed time  (implicit): 00:00:00.7165567
    Elapsed time (reference): 00:00:03.7519285
    Elapsed time      (uint): 00:00:00.6347374