Skip to content

Instantly share code, notes, and snippets.

@jtheisen
Created September 15, 2016 13:24
Show Gist options
  • Save jtheisen/433660535e00a77d949646cd23fae7b5 to your computer and use it in GitHub Desktop.
Save jtheisen/433660535e00a77d949646cd23fae7b5 to your computer and use it in GitHub Desktop.
Value type generic performance benchmark
void Main()
{
var t1 = DateTime.Now;
TestGeneric(new GenericComparer<Int32>());
var t2 = DateTime.Now;
TestGeneral(new GenericComparer<Int32>());
var t3 = DateTime.Now;
TestGeneric(Comparer<Int32>.Default);
var t4 = DateTime.Now;
TestGeneral(Comparer<Int32>.Default);
var t5 = DateTime.Now;
(t2 - t1).Dump("Generic with value-typed comparer");
(t3 - t2).Dump("General with value-typed comparer");
(t4 - t3).Dump("Generic with reference-typed comparer");
(t5 - t4).Dump("General with reference-typed comparer");
}
Int32 count = 10000000;
void TestGeneric<Comparer>(Comparer comparer)
where Comparer : IComparer<Int32>
{
for (int i = 0 ; i < count; ++i)
comparer.Compare(42, 24);
}
void TestGeneral(IComparer<Int32> comparer)
{
for (int i = 0 ; i < count; ++i)
comparer.Compare(42, 24);
}
struct GenericComparer<T> : IComparer<T>
where T : IComparable<T>
{
public int Compare(T x, T y) {
return x.CompareTo(y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment