为什么.NET中的数组比列表快得多?

时间:2017-01-09 12:51:31

标签: c# arrays performance list capacity

请考虑以下代码:

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace ListAllocationPerformance
{
    class Program
    {
        const int count = 100000000;

        public static object Memory { get; private set; }

        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("count: {0}", count));
            MeasureFunction(FillListWithoutAllocation, "without allocation");
            MeasureFunction(FillListWithAllocation, "with allocation");
            MeasureFunction(FillArray, "array");
            MeasureFunction(FillUnmanagedArray, "unsafe array");
            string input = Console.ReadLine();
        }

        static void MeasureFunction(Action function, string name)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            function();
            stopwatch.Stop();
            Console.WriteLine(string.Format("Function {0} finished after \t {1}ms", name, stopwatch.ElapsedMilliseconds, count));
        }

        static void FillListWithoutAllocation()
        {
            List<int> list = new List<int>();
            for (int i = 0; i < count; i++) list.Add(i);
        }

        static void FillListWithAllocation()
        {
            List<int> list = new List<int>(count);
            for (int i = 0; i < count; i++) list.Add(i);
        }

        static void FillArray()
        {
            int[] array = new int[count];
            for (int i = 0; i < count; i++) array[i] = i;
        }

        static void FillUnmanagedArray()
        {
            unsafe
            {
                int[] array = new int[count];
                fixed(int* ptr = array)

                for (int i = 0; i < count; i++) *ptr = i;
            }
        }
    }
}

发布版本的结果令人惊叹:

count: 100000000
Function without allocation finished after       871ms
Function with allocation finished after          684ms
Function array finished after                    168ms
Function unsafe array finished after              91ms

到目前为止,阵列甚至优于预先分配的列表!我认为这个列表基本上是一个阵列 - 但结果如何差异呢?

0 个答案:

没有答案