Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Just to put the topic to rest (yes, the question was posed 8 months ago, but the internet always knows!), I decided to run a little test for which is more efficient <strong><em>if</em></strong> you're pretty sure you won't have an exception -- e.g., the "else" part is going to only happen 0.001% of the time. As it turns out, if you <em>never</em> have to catch/else anything, the try-catch is about 4% faster (on my machine, anyway). Here's the code and the accompanying results:</p> <p><strong>CASE 1: if-else:</strong></p> <pre><code>var startTime = DateTime.Now; int bazillion = 100000000; int[] list = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; for (int i = 0; i &lt; bazillion; i++) { for (int k = 0; k &lt; list.Length; k++) { if (k &gt;= 0) { list[k] = i; } else { // do nothing. } } } var executionTime = DateTime.Now - startTime; Debug.WriteLine (executionTime.TotalMilliseconds); </code></pre> <p>Execution times (milliseconds) on 5 runs: 7441.4256, 7392.4228, 7545.4316, 7531.4308, 7323.4188.<br> Average = <strong>7446.82592 milliseconds</strong></p> <p><br/> <strong>CASE 2: try-catch:</strong></p> <pre><code>var startTime = DateTime.Now; int bazillion = 100000000; int[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; for (int i = 0; i &lt; bazillion; i++) { for (int k = 0; k &lt; list.Length; k++) { try { list[k] = i; } catch (Exception e) { // do nothing } } } var executionTime = DateTime.Now - startTime; Debug.WriteLine(executionTime.TotalMilliseconds); </code></pre> <p>Execution times (milliseconds) on 5 runs: 7258.4152, 7137.4083, 7070.4044, 7052.4033, 7120.4073 Average = <strong>7127.8077 milliseconds</strong></p> <p><br/> <strong>Conclusion</strong> <em>(based on this rather simplistic example; actual mileage may vary, etc)</em>: <br/> In terms of sheer numbers, <em>if</em> you're pretty dang sure that the exception/else case will not occur, try-catch is about 4% faster than having to execute the "if" clause every single time.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload