Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is Array.Sort() so slow compared to LINQ?
    primarykey
    data
    text
    <p>I made quick testing application to compare LINQ sorting to Array.Sort on my custom objects. Array.Sort seems extremely slow!</p> <p>I made my custom class like this:</p> <pre><code>class Person : IComparable&lt;Person&gt; { public int Age { get; set; } public string Name { get; set; } public int CompareTo(Person obj) { return this.Age.CompareTo(obj.Age); } public Person() { } } </code></pre> <p>Then i made my testing persons in main() :</p> <pre><code>string name = "Mr. Tomek"; Random r = new Random(); int size = 10000000; DateTime start, end; Person[] people1 = new Person[size]; Person[] people2 = new Person[size]; for (int i = 0; i &lt; size; i++) { people1[i] = new Person(); people1[i].Age = r.Next(0, 10000); people1[i].Name = name; people2[i] = new Person(); people2[i].Age = people1[i].Age; people2[i].Name = people1[i].Name; } </code></pre> <p>After that i have measured time taken to Sort by Array.Sort and by LINQ:</p> <pre><code>start = DateTime.Now; var sort = from s in people2 orderby s.Age select s; end = DateTime.Now; Console.WriteLine("LINQ: "); Console.WriteLine((end - start).TotalMilliseconds); start = DateTime.Now; Array.Sort(people1,((Person p1, Person p2)=&gt;{return p1.CompareTo(p2);})); end = DateTime.Now; Console.WriteLine("IComparable: "); Console.WriteLine((end - start).TotalMilliseconds); Console.ReadLine(); </code></pre> <p>Linq time: about 1 or 2 miliseconds</p> <p>Array.Sort: over 16 <strong>SECONDS!</strong></p> <p>All arrays are sorted (LINQ produces new collection and leaves oryginal array unsorted) but Array.Sort is extremely slow! How could it be explained? (in DEBUG and RELEASE mode Array.Sort fails extremely)</p> <p>I pasted code with lambda expression when sorting with Array.Sort but it's the same with and without it. (Class Person implements IComparable interface)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload