Today I realized something that seemed strange to me: I noticed that when I just do
try { doSomething(); } catch (Exception e) { }
he is not slower than if I just did
doSomething();
So, I ran the test and wrote some quick code to prove what I saw, the code basically just loops on a function called doSomething () many times, once without and once with the try-catch environment. So, here is the code if you want to test it yourself:
public class Main { private static final long LOOPS = 1000000L; public static final void main(String[] args) { System.out.println("Loop without try catch: "+loopWithoutTryCatch(LOOPS)); System.out.println("Loop with try catch: "+loopWithTryCatch(LOOPS)); } public static long loopWithoutTryCatch(long loops) { long startTime = System.currentTimeMillis(); for (long i = 0L; i < loops; i++) { doSomething(); } return System.currentTimeMillis()-startTime; } public static long loopWithTryCatch(long loops) { long startTime = System.currentTimeMillis(); for (long i = 0L; i < loops; i++) { try { doSomething(); } catch (Exception e) { } } return System.currentTimeMillis()-startTime; } public static void doSomething() { for (int i = 0; i < 250; i++) { if (i % 3 == 0) { i++; } } } }
And I got the following output:
Loop without try catch: 375 Loop with try catch: 373
I was surprised, so I tested it again and again, but I always had the same results, in both cases it works pretty much at the same time.
And now my question is: why?
I really don't understand this, as far as I know, try-catch writes resources before being used in some table to a later version - if any exception is thrown - be able to clear it and refer to the values that it had before the exception occurred.
It will take at least some time, right? I thought it was possible because I didn’t represent it randomly in the random example that I choose, and in this particular case, in which I tested it, it doesn’t slow anything down, but it was unlikely for me.
Then I thought that it might take only a tiny amount of time, that this is not noticeable with the number of “few” executions, so I ran the test program again with a total of 10 million cycles, but what I found was just that I already found: for both versions it takes about the same time.
So, is there a logical explanation for this, or is it just a try-catch behavior of a particular type?
Thanks for any clarification in advance.