Dot-Net

數組與列表的性能

  • January 18, 2009

假設您需要一個需要經常迭代的整數列表/數組,我的意思是非常頻繁。原因可能會有所不同,但可以說它是大容量處理的最內部循環的核心。

一般來說,由於大小的靈活性,人們會選擇使用列表(List)。最重要的是,msdn 文件聲稱列表在內部使用了一個數組,並且應該同樣快地執行(快速瀏覽一下 Reflector 就證實了這一點)。然而,這涉及到一些成本。

有人真的測量過這個嗎?在列表中迭代 6M 次是否會與數組花費相同的時間?

非常容易測量…

在我知道長度是固定的少數緊密循環處理程式碼中,我使用數組來進行額外的微小優化;如果您使用索引器 / 用於表單,數組可能會稍微快一些 - 但 IIRC 認為這取決於數組中的數據類型。但是除非您需要進行微優化,否則請保持簡單並使用等。List<T>

當然,這只適用於讀取所有數​​據的情況;對於基於鍵的查找,字典會更快。

這是我使用“int”的結果(第二個數字是校驗和,以驗證它們都做了相同的工作):

(已編輯以修復錯誤)

List/for: 1971ms (589725196)
Array/for: 1864ms (589725196)
List/foreach: 3054ms (589725196)
Array/foreach: 1860ms (589725196)

基於測試台:

using System;
using System.Collections.Generic;
using System.Diagnostics;
static class Program
{
   static void Main()
   {
       List<int> list = new List<int>(6000000);
       Random rand = new Random(12345);
       for (int i = 0; i < 6000000; i++)
       {
           list.Add(rand.Next(5000));
       }
       int[] arr = list.ToArray();

       int chk = 0;
       Stopwatch watch = Stopwatch.StartNew();
       for (int rpt = 0; rpt < 100; rpt++)
       {
           int len = list.Count;
           for (int i = 0; i < len; i++)
           {
               chk += list[i];
           }
       }
       watch.Stop();
       Console.WriteLine("List/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

       chk = 0;
       watch = Stopwatch.StartNew();
       for (int rpt = 0; rpt < 100; rpt++)
       {
           for (int i = 0; i < arr.Length; i++)
           {
               chk += arr[i];
           }
       }
       watch.Stop();
       Console.WriteLine("Array/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

       chk = 0;
       watch = Stopwatch.StartNew();
       for (int rpt = 0; rpt < 100; rpt++)
       {
           foreach (int i in list)
           {
               chk += i;
           }
       }
       watch.Stop();
       Console.WriteLine("List/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

       chk = 0;
       watch = Stopwatch.StartNew();
       for (int rpt = 0; rpt < 100; rpt++)
       {
           foreach (int i in arr)
           {
               chk += i;
           }
       }
       watch.Stop();
       Console.WriteLine("Array/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

       Console.ReadLine();
   }
}

引用自:https://stackoverflow.com/questions/454916