## 数组排序方法的性能比较（1）：注意事项及试验

2010-01-21 00:11  Jeffrey Zhao  阅读(11363)  评论(55编辑  收藏  举报

# 重新测试

static T[] CloneArray<T>(T[] source)
{
var dest = new T[source.Length];
Array.Copy(source, dest, source.Length);
return dest;
}

Array.Sort<T>方法其实有两“类”重载，一类是使用IComparer<T>对象进行比较，而另一类则使用了Comparison<T>这个委托对象进行比较。为此，我们构造一个Int32Comparer类来实现IComparer<int>接口：

private class Int32Comparer : IComparer<int>
{
#region IComparer<int> Members

public int Compare(int x, int y)
{
return x - y;
}

#endregion
}

static void SortWithCustomComparer(int[] array)
{
Array.Sort(array, new Int32Comparer());
}

static void SortWithDelegate(int[] array)
{
Array.Sort(array, (x, y) => x - y);
}

static void SortWithDefaultComparer(int[] array)
{
Array.Sort(array, Comparer<int>.Default);
}

static void SortWithLinq(int[] array)
{
var sorted =
(from i in array
orderby i
select i).ToList();
}

static void Main(string[] args)
{
var random = new Random(DateTime.Now.Millisecond);
var array = Enumerable.Repeat(0, 1000 * 500).Select(_ => random.Next()).ToArray();

CodeTimer.Initialize();

CodeTimer.Time("SortWithDefaultComparer", 100,
() => SortWithDefaultComparer(CloneArray(array)));

CodeTimer.Time("SortWithCustomComparer", 100,
() => SortWithCustomComparer(CloneArray(array)));

CodeTimer.Time("SortWithDelegate", 100,
() => SortWithDelegate(CloneArray(array)));

CodeTimer.Time("SortWithLinq", 100,
() => SortWithLinq(CloneArray(array)));

}

# 试验结果

SortWithDefaultComparer
Time Elapsed:   7,662ms
Gen 0:          49
Gen 1:          49
Gen 2:          49

SortWithCustomComparer
Time Elapsed:   13,847ms
Gen 0:          49
Gen 1:          49
Gen 2:          49

SortWithDelegate
Time Elapsed:   19,625ms
Gen 0:          49
Gen 1:          49
Gen 2:          49

SortWithLinq
Time Elapsed:   31,785ms
Gen 0:          99
Gen 1:          99
Gen 2:          99