我可以使用Sort或OrderBy对列表进行排序。哪一个更快?两者都在使用相同的算法吗?
List<Person> persons = new List<Person>(); persons.Add(new Person("P005", "Janson")); persons.Add(new Person("P002", "Aravind")); persons.Add(new Person("P007", "Kazhal"));
1。
persons.Sort((p1,p2)=>string.Compare(p1.Name,p2.Name,true));
2。
var query = persons.OrderBy(n => n.Name, new NameComparer()); class NameComparer : IComparer<string> { public int Compare(string x,string y) { return string.Compare(x, y, true); } }
为什么不测量它:
class Program { class NameComparer : IComparer<string> { public int Compare(string x, string y) { return string.Compare(x, y, true); } } class Person { public Person(string id, string name) { Id = id; Name = name; } public string Id { get; set; } public string Name { get; set; } } static void Main() { List<Person> persons = new List<Person>(); persons.Add(new Person("P005", "Janson")); persons.Add(new Person("P002", "Aravind")); persons.Add(new Person("P007", "Kazhal")); Sort(persons); OrderBy(persons); const int COUNT = 1000000; Stopwatch watch = Stopwatch.StartNew(); for (int i = 0; i < COUNT; i++) { Sort(persons); } watch.Stop(); Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); for (int i = 0; i < COUNT; i++) { OrderBy(persons); } watch.Stop(); Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds); } static void Sort(List<Person> list) { list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true)); } static void OrderBy(List<Person> list) { var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray(); } }
在我的计算机上,以“发布”模式编译时,该程序将打印:
Sort: 1162ms OrderBy: 1269ms
更新:
正如@Stefan所建议的,这是对大列表进行较少排序的结果:
List<Person> persons = new List<Person>(); for (int i = 0; i < 100000; i++) { persons.Add(new Person("P" + i.ToString(), "Janson" + i.ToString())); } Sort(persons); OrderBy(persons); const int COUNT = 30; Stopwatch watch = Stopwatch.StartNew(); for (int i = 0; i < COUNT; i++) { Sort(persons); } watch.Stop(); Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); for (int i = 0; i < COUNT; i++) { OrderBy(persons); } watch.Stop(); Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
印刷品:
Sort: 8965ms OrderBy: 8460ms
在这种情况下,看起来OrderBy表现更好。
UPDATE2:
并使用随机名称:
List<Person> persons = new List<Person>(); for (int i = 0; i < 100000; i++) { persons.Add(new Person("P" + i.ToString(), RandomString(5, true))); }
哪里:
private static Random randomSeed = new Random(); public static string RandomString(int size, bool lowerCase) { var sb = new StringBuilder(size); int start = (lowerCase) ? 97 : 65; for (int i = 0; i < size; i++) { sb.Append((char)(26 * randomSeed.NextDouble() + start)); } return sb.ToString(); }
产量:
Sort: 8968ms OrderBy: 8728ms
仍然OrderBy更快