Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. /* output with .NET 4.0 on 2014 beefy machine x86 release build:
  2. Test1 - Activator.CreateInstance<T>(): 8642
  3. Test2 - new T() 864
  4. Test3 - Delegate 1156
  5. Test4 - Generic new() 8858
  6. Baseline 327
  7. */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Diagnostics;
  14.  
  15. namespace ConsoleApplication1
  16. {
  17. class Program
  18. {
  19. static void Main(string[] args)
  20. {
  21. const int IterationCount = 100000000;
  22.  
  23. // warmup
  24. Test1();
  25. Test2();
  26. Test3();
  27. Test4<TestClass>();
  28.  
  29. // profile Activator.CreateInstance<T>()
  30. Stopwatch sw = Stopwatch.StartNew();
  31. for (int index = 0; index < IterationCount; index++)
  32. Test1();
  33. sw.Stop();
  34. Console.WriteLine("Test1 - Activator.CreateInstance<T>(): {0}", sw.ElapsedMilliseconds);
  35.  
  36. // profile new T()
  37. sw.Restart();
  38. for (int index = 0; index < IterationCount; index++)
  39. Test2();
  40. sw.Stop();
  41. Console.WriteLine("Test2 - new T() {0}", sw.ElapsedMilliseconds);
  42.  
  43. // profile Delegate
  44. sw.Restart();
  45. for (int index = 0; index < IterationCount; index++)
  46. Test3();
  47. sw.Stop();
  48. Console.WriteLine("Test3 - Delegate {0}", sw.ElapsedMilliseconds);
  49.  
  50. // profile generic new()
  51. sw.Restart();
  52. for (int index = 0; index < IterationCount; index++)
  53. Test4<TestClass>();
  54. sw.Stop();
  55. Console.WriteLine("Test4 - Generic new() {0}", sw.ElapsedMilliseconds);
  56.  
  57. // profile Baseline
  58. sw.Restart();
  59. for (int index = 0; index < IterationCount; index++)
  60. TestBaseline();
  61. sw.Stop();
  62. Console.WriteLine("Baseline {0}", sw.ElapsedMilliseconds);
  63. }
  64.  
  65. public static void Test1()
  66. {
  67. var obj = Activator.CreateInstance<TestClass>();
  68. GC.KeepAlive(obj);
  69. }
  70.  
  71. public static void Test2()
  72. {
  73. var obj = new TestClass();
  74. GC.KeepAlive(obj);
  75. }
  76.  
  77. static Func<TestClass> Create = delegate
  78. {
  79. return new TestClass();
  80. };
  81.  
  82. public static void Test3()
  83. {
  84. var obj = Create();
  85. GC.KeepAlive(obj);
  86. }
  87.  
  88. public static void Test4<T>() where T : new()
  89. {
  90. var obj = new T();
  91. GC.KeepAlive(obj);
  92. }
  93.  
  94. static TestClass x = new TestClass();
  95. public static void TestBaseline()
  96. {
  97. GC.KeepAlive(x);
  98. }
  99.  
  100. public class TestClass
  101. {
  102. }
  103. }
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement