为什么的Array.Sort()如此缓慢相比,LINQ? [英] Why is Array.Sort() so slow compared to LINQ?

查看:146
本文介绍了为什么的Array.Sort()如此缓慢相比,LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了快速测试应用程序来比较LINQ到排序上的Array.sort我的自定义对象。
似乎的Array.Sort极其缓慢!

I made quick testing application to compare LINQ sorting to Array.Sort on my custom objects. Array.Sort seems extremely slow!

我做了我的自定义类是这样的:

I made my custom class like this:

class Person : IComparable<Person>
{
    public int Age { get; set; }
    public string Name { get; set; }

    public int CompareTo(Person obj)
    {
        return this.Age.CompareTo(obj.Age);
    }

    public Person()
    { }

}

然后我做了我的测试者的main():

Then i made my testing persons in main() :

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 < 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;
}

这之后,我有分寸采取至按的Array.Sort和LINQ时间:

After that i have measured time taken to Sort by Array.Sort and by LINQ:

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)=>{return p1.CompareTo(p2);}));
end = DateTime.Now;

Console.WriteLine("IComparable: ");
Console.WriteLine((end - start).TotalMilliseconds);

Console.ReadLine();

Linq的时间:大约1或2毫秒

Linq time: about 1 or 2 miliseconds

的Array.Sort:16岁以上的

Array.Sort: over 16 SECONDS!

所有的数组进行排序(LINQ产生新的收集和叶oryginal数组排序的),但的Array.Sort是非常慢!怎么会解释呢? (在调试和发布模式的Array.Sort极其失败)

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)

我粘贴code。与前拉姆达pression用的Array.Sort排序时,但它的使用和不使用它一样。 (Person类实现IComparable接口)

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)

推荐答案

您Linq查询甚至没有得到执行,因为你没有得到的结果。这就是所谓的延迟执行。当你真正枚举的结果,才能执行查询。

Your Linq query doesn't even get executed because you don't get the results. That's called deferred execution. The query is only executed when you actually enumerate over the results.

使用类似 VAR的结果= sort.ToArray()来执行查询,那么你会得到更准确的结果。

Use something like var results = sort.ToArray() to execute the query, then you will get more accurate results.

这篇关于为什么的Array.Sort()如此缓慢相比,LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆