为什么.NET中的数组比列表快得多?
为什么.NET中的数组比列表快得多?
考虑以下代码:
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() { Listlist = new List (); for (int i = 0; i < count; i++) list.Add(i); } static void FillListWithAllocation() { List list = new List (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
数组的性能甚至远远超过预先分配的列表!我以为列表在内部基本上是一个数组,但为什么结果差别这么大呢?