using System; using System.Diagnostics; using System.Linq; #pragma warning disable 0169 public class SmallClass { int x; } public class LargeClass { long a, b, c, d, e, f, g, h; } public struct SmallStruct { int x; } public struct LargeStruct { long a, b, c, d, e, f, g, h; } #pragma warning restore 0169 public class Benchmark { static Action[] Tests = { SmallStructWithConstraint, SmallStructWithProvider, LargeStructWithConstraint, LargeStructWithProvider, SmallClassWithConstraint, SmallClassWithProvider, LargeClassWithConstraint, LargeClassWithProvider, }; private static void SmallStructWithConstraint() { MakeInstance(); } private static void SmallStructWithProvider() { MakeInstance(() => new SmallStruct()); } private static void LargeStructWithConstraint() { MakeInstance(); } private static void LargeStructWithProvider() { MakeInstance(() => new LargeStruct()); } private static void SmallClassWithConstraint() { MakeInstance(); } private static void SmallClassWithProvider() { MakeInstance(() => new SmallClass()); } private static void LargeClassWithConstraint() { MakeInstance(); } private static void LargeClassWithProvider() { MakeInstance(() => new LargeClass()); } private static void MakeInstance() where T : new() { T t = new T(); UseValue(t); } private static void MakeInstance(Func provider) where T : new() { T t = provider(); UseValue(t); } private static void UseValue(T instance) { // Do nothing... } // -------------- INFRASTRUCTURE BELOW HERE -------------- const int Iterations = 100000000; static void Main() { Console.WriteLine("Environment: CLR {0} on {1}", Environment.Version, Environment.OSVersion); // Warm up RunTests(1, false, 0); int maxMethodLength = Tests.Select(x => x.Method.Name.Length).Max(); // Real thing RunTests(Iterations, true, maxMethodLength); } static void RunTests(int count, bool displayResults, int maxLength) { foreach (Action action in Tests) { Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { action(); } sw.Stop(); if (displayResults) { Console.WriteLine("{0}: {1}ms", action.Method.Name.PadRight(maxLength), ((int) sw.ElapsedMilliseconds).ToString().PadLeft(6)); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } } }