C#性能,内存缓冲区的数组与跨度

我正在测试使用标准C#阵列与使用内存缓冲区的性能。标准阵列获胜。我不知道标准数组比使用内存缓冲区的跨度更快。该文档说应该在高性能方案中使用内存缓冲区。我正在使用发布优化配置。

class Program
{
    private static void MemoryPoolTest(IMemoryOwner<long> owner)
    {
        for (var i = 0; i < 100; i++)
        {
            var innerCounter = 0;
            for (var j = 0; j < 1000; j++)
            {
                if (j % 3 == 0)
                {
                    owner.Memory.Span[innerCounter++] = DateTime.UtcNow.Ticks;
                }
            }
            var result = owner.Memory.Slice(0, innerCounter - 1);
        }
    }

    private static void ArrayTest()
    {
        for (var i = 0; i < 100; i++)
        {
            var innerCounter = 0;
            Span<long> array = new long[1000];
            for (var j = 0; j < 1000; j++)
            {
                if (j % 3 == 0)
                {
                    array[innerCounter++] = DateTime.UtcNow.Ticks;
                }
            }
            var result = array.Slice(0, innerCounter - 1);
        }
    }

    static void Main(string[] args)
    {
        Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
        var m = new List<long>();
        var a = new List<long>();
        var sw = new Stopwatch();
        using var owner = MemoryPool<long>.Shared.Rent(1000);
        for (var i = 0; i < 1000; i++)
        {
            sw.Restart();
            MemoryPoolTest(owner);
            sw.Stop();
            m.Add(sw.ElapsedTicks);
            sw.Restart();
            ArrayTest();
            sw.Stop();
            a.Add(sw.ElapsedTicks);
        }
        Console.WriteLine(m.Skip(10).Average());
        Console.WriteLine(a.Skip(10).Average());
    }
}
评论