ListのSortメソッドとLINQのOrderByメソッドの速度検証

  1. using System;
  2. using System.Text;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. namespace ConsoleApplication1
  7. {
  8.     class Program
  9.     {
  10.         /// 
  11.         /// ListのSortメソッドとLINQのOrderByメソッドの速度検証
  12.         /// 
  13.         /// 
  14.         static void Main(string[] args)
  15.         {
  16.             List list = new List();
  17.             // 1000万件データ作成
  18.             for (int i = 10000000; i > 0; i-- )
  19.             {
  20.                 list.Add(i);
  21.             }
  22.             Stopwatch sw = new Stopwatch();
  23.             sw.Start();
  24.             list.Sort();
  25.             sw.Stop();
  26.             Console.WriteLine("Sortメソッド:" + sw.Elapsed + "秒");
  27.             List list2 = new List();
  28.             // 1000万件データ作成
  29.             for (int i = 10000000; i > 0; i--)
  30.             {
  31.                 list2.Add(i);
  32.             }
  33.             sw.Restart();
  34.             IOrderedEnumerable tmp = list2.OrderBy(n => n);
  35.             sw.Stop();
  36.             Console.WriteLine("OrderByメソッド:" + sw.Elapsed + "秒");
  37.             sw.Restart();
  38.             list2 = tmp.ToList();
  39.             sw.Stop();
  40.             Console.WriteLine("IOrderedEnumerableをListに変換:" + sw.Elapsed + "秒");
  41.             Console.ReadLine(); 
  42.         }
  43.     }
  44. }
意外?にもSortよりもLINQのOrderByの方が速い!!
但し、ToListでList型に変換するのは非常に遅い。
なので、IOrderedEnumerableで問題ない場合はOrderByを使った方が良いが、
List型じゃないと困る!!という場合はSortを使用した方が良い。

image

戻る