Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are not testing the computational cost of the <code>try/catch</code> block. You are really testing the cost of <strong>exception handling</strong>. A fair test would be making <code>b= 2 ;</code> also in <code>ExceptionCase</code>. I don't know what extremely wrong conclusions you will draw if you think you are testing only <code>try/catch</code>. I'm frankly alarmed.</p> <p>The reason why timing changes so much is that you are executing the functions so many times that the JVM decided to compile and optimize them. Enclose your loop into an outer one</p> <pre><code> for(int e= 0 ; e &lt; 17 ; e++ ) { for(int i= 0 ; i &lt; arr.length ; i++) { System.out.println(arr[i] + "," + NormalCase(arr[i]) + "," + ExceptionCase(arr[i])); } } </code></pre> <p>and you will see more stable results by the end of the run.</p> <p>I also think that in the case <code>NormalCase</code> the optimizer is "realizing" that the <code>for</code> is not really doing anything and just skipping it (for an execution time of 0). For some reason (probably the side effect of exceptions), it's not doing the same with <code>ExceptionCase</code>. To solve this bias, compute something inside the loop and return it.</p> <p>I don't want to change your code too much, so I'll use a trick to return a second value:</p> <pre><code> public static long NormalCase(int times,int[] result) { long firstTime=System.nanoTime(); int computation= 0 ; for(int i= 0; i &lt; times; i++ ) { int a= i + 1 ; int b= 2 ; a= a / b ; computation+= a ; } result[0]= computation ; return System.nanoTime()-firstTime; } </code></pre> <p>You can call this with <code>NormalCase(arr[i],result)</code>, preceded by declaration <code>int[] result= new int[1] ;</code>. Modify <code>ExceptionCase</code> in the same way, and <strong>output</strong> <code>result[0]</code> to avoid any other optimization. You will probably need one <code>result</code> variable for each function.</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