gpt4 book ai didi

c# - 为什么 Enumerable.OrderBy 方法在不使用比较器时工作得更快

转载 作者:行者123 更新时间:2023-11-30 13:03:55 25 4
gpt4 key购买 nike

我写了排序方法的代码测试速度。它生成一个集合并使用不同的方法对其进行排序。

public void TestMethod1()
{
var unsortedCollection = GenerateCollection();

var toSort = unsortedCollection.ToList();
Console.WriteLine("OrderBy x.A: " + Measure(() => toSort.OrderBy(x => x.A).ToArray()) + "ms");
toSort = unsortedCollection.ToList();
Console.WriteLine("OrderBy x: " + Measure(() => toSort.OrderBy(x => x).ToArray()) + "ms");
toSort = unsortedCollection.ToList();
Console.WriteLine("OrderBy x using Comparer: " + Measure(() => toSort.OrderBy(x => x, new Comparer()).ToArray()) + "ms");
toSort = unsortedCollection.ToList();
Console.WriteLine("OrderBy x using Comparer<int>.Default: " + Measure(() => toSort.OrderBy(x => x.A, Comparer<int>.Default).ToArray()) + "ms");
toSort = unsortedCollection.ToList();
Console.WriteLine("OrderBy x using Comparer<SimpleObject>.Default: " + Measure(() => toSort.OrderBy(x => x, Comparer<SimpleObject>.Default).ToArray()) + "ms");

toSort = unsortedCollection.ToList();
Console.WriteLine("Sort: " + Measure(() =>
{
toSort.Sort();
toSort.ToArray();
}) + "ms");
toSort = unsortedCollection.ToList();
Console.WriteLine("Sort using Comparison: " + Measure(() =>
{
toSort.Sort((x, y) => x.A.CompareTo(y.A));
toSort.ToArray();
}) + "ms");
toSort = unsortedCollection.ToList();
Console.WriteLine("Sort using Comparer: " + Measure(() =>
{
toSort.Sort(new Comparer());
toSort.ToArray();
}) + "ms");

}

private List<SimpleObject> GenerateCollection()
{
int length = 10000000;
var list = new List<SimpleObject>();
for (int i=0; i<length; i++)
{
list.Add(new SimpleObject());
}
return list;
}

private long Measure(Action method)
{
Stopwatch sw = new Stopwatch();
sw.Reset();
sw.Start();
method();
sw.Stop();
return sw.ElapsedMilliseconds;
}

public class Comparer: IComparer<SimpleObject>
{
public int Compare(SimpleObject x, SimpleObject y)
{
return x.A.CompareTo(y.A);
}
}
public class SimpleObject: IComparable<SimpleObject>
{
public int A;
private static Random rand = new Random();
private const int maxValue = 1000000;

public SimpleObject()
{
A = rand.Next(maxValue);
}

public int CompareTo(SimpleObject other)
{
return A.CompareTo(other.A);
}
}

结果如下:

OrderBy x.A: 8732ms
OrderBy x: 19136ms
OrderBy x using Comparer: 17054ms
OrderBy x using Comparer<int>.Default: 8758ms
OrderBy x using Comparer<SimpleObject>.Default: 19817ms
Sort: 8000ms
Sort using Comparison: 9515ms
Sort using Comparer: 8990ms

我想知道为什么使用 Comparer 的 OrderBy 工作时间比不使用 Comparer 的时间长,为什么使用 Comparison 的 Sort 比使用 Comparer 工作的时间长。

最佳答案

这似乎是对象比较的问题。 OrderBy 方法缓存键。 int 键比较快,object 键比较长。

关于c# - 为什么 Enumerable.OrderBy<TSource, TKey> 方法在不使用比较器时工作得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11152795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com