Sunday 15 July 2012

.net - C# Sort and OrderBy comparison -


I can sort a list through sort or orderby which is fast? Are both working on the same algorithm?

  list & lt; Person & gt; Person = new list & lt; Person & gt; (); person. Add (New Person ("P005", "Johnson")); person. Add (New Person ("P 002", "Arvind")); person. Add (New Person ("P007", "Cashel"));  

1.

  individuals.Sort ((p1, p2) => string .compair (p1.Name, p2.Name, true));  

2.

  var query = persons.OrderBy (n = & gt; n.Name, new NameComparer ()); Class name compairer: iCompair & lt; String & gt; {Public int comparison (string x, string y) {return string Computer (x, y, true); }}  

Why not measure it:

  Classroom program {class NameComparer: IComparer & lt; String & gt; {Public int comparison (string x, string y) {return string Computer (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; }} Fixed Zero Main () {List & lt; Person & gt; Person = new list & lt; Person & gt; (); person. Add (New Person ("P005", "Johnson")); person. Add (New Person ("P 002", "Arvind")); person. Add (New Person ("P007", "Cashel")); Sort (person); OrderBy (person); Const int COUNT = 1000000; Stopwatch clock = stopwatch Startup (); For (int i = 0; i  

This program prints on my computer when it is released in release mode:

  Sort: 1162 Order-Order: 1269ms  

Update:

As suggested by @tefan, this is the result of a short list sorting:

  list & lt; Person & gt; Person = new list & lt; Person & gt; (); {Individuals.Add (new person ("P" + i.ToString (), "Jason" + i.ToString ()) for (Int i = 0; I & lt; 100000; i ++); } Sort (Individuals); OrderBy (person); Const int COUNT = 30; Stopwatch clock = stopwatch Startup (); For (int i = 0; i  

Print:

  Sort: 8965ms Order-B: 8460ms  

In this scenario it seems that OrderBy performs better


UPDATE2:

and using random names:

  list & lt; Person & gt; Person = new list & lt; Person & gt; (); {Individuals.Add (new person ("P" + i.ToString (), random string (5, true)) for (Int i = 0; I & lt; 100000; i ++); }  

Where:

  Private static random randomSeed = new Random (); Public stable string ramstring (integer shape, bold lower case) {var sb = new stringbilder (size); Int start = (lowerCase)? 97: 65; For (int i = 0; i  

Yield:

  Sort: 8968 Order order: 8728ms  

Still order b is fast < / P>


No comments:

Post a Comment