fork(1) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6.  
  7. namespace ThrowPerf
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. var stp = new Stopwatch();
  14. stp.Start();
  15.  
  16. for (var i = 0; i < 10000; i++)
  17. {
  18. try
  19. {
  20. // base cost
  21. // try
  22. {
  23. doTry();
  24. goto failed;
  25. }
  26. // catch
  27. failed:
  28. {
  29. doCleanup();
  30. }
  31. }
  32. catch { }
  33. }
  34.  
  35. stp.Stop();
  36. Console.WriteLine("Method call+goto: {0}", stp.Elapsed);
  37. stp.Reset();
  38. stp.Start();
  39.  
  40. for (var i = 0; i < 10000; i++)
  41. {
  42. try
  43. {
  44. // catch
  45. try
  46. {
  47. doTryFail();
  48. }
  49. catch
  50. {
  51. doCleanup();
  52. }
  53. }
  54. catch { }
  55. }
  56.  
  57. stp.Stop();
  58. Console.WriteLine("Try/Catch: {0}", stp.Elapsed);
  59. stp.Reset();
  60. stp.Start();
  61.  
  62. for (var i = 0; i < 10000; i++)
  63. {
  64. try
  65. {
  66. bool suceeded = false;
  67. // finally
  68. try
  69. {
  70. doTryFail();
  71. suceeded = true;
  72. }
  73. finally
  74. {
  75. if (!suceeded)
  76. doCleanup();
  77. }
  78. }
  79. catch { }
  80. }
  81.  
  82. stp.Stop();
  83. Console.WriteLine("Try/Flag/Finally: {0}", stp.Elapsed);
  84. stp.Reset();
  85. stp.Start();
  86. Console.ReadLine();
  87. }
  88.  
  89. // the purpose of checking datetime is just to ensure the call does
  90. // not get optimized out. Otherwise, it does not matter.
  91. private static void doTryFail()
  92. {
  93. if (System.DateTime.Now.Year == 0)
  94. Console.WriteLine("foobar");
  95. throw new NotImplementedException();
  96. }
  97.  
  98. private static void doCleanup()
  99. {
  100. if (System.DateTime.Now.Year == 0)
  101. Console.WriteLine("foobar");
  102. }
  103.  
  104. private static void doTry()
  105. {
  106. if (System.DateTime.Now.Year == 0)
  107. Console.WriteLine("foobar");
  108. }
  109. }
  110. }
  111.  
Success #stdin #stdout 0.14s 35048KB
stdin
Standard input is empty
stdout
Method call+goto: 00:00:00.0173153
Try/Catch: 00:00:00.0427985
Try/Flag/Finally: 00:00:00.0423863