Does trying-catch block placement affect performance?

Does trying-catch block placement affect performance?

EXAMPLE 1: try-catch block inside a while loop

while (true) { try { // ... read from a file } catch (EOFException e) { break; } } 

EXAMPLE 2: a try-catch block surrounds a while loop

 try { while (true) { // ... read from a file } } catch (EOFException e) { // :P } 

Logically, these two examples are equivalent, but what should I prefer?

+6
java performance try-catch
source share
5 answers

Should java try blocks be used as much as possible?

This gives a much better answer than I could. Other than this, they only add a record to the table, which checks when exceptions are thrown, so if the exception is not thrown, they do not affect performance. It would be better to just place it wherever you try to restore, if you can. If not, wherever it is useful or makes sense. Although with a break outside the cycle, I do not think that the second is valid anyway.

+3
source share

Whatever the overhead of try-catch is probably insignificant, but what attracts my attention more in the first case is that it is misleading: you catch the exception just to break the loop. I would choose solution 2 only because it is consistent with intention. And you avoid overhead in this way.

+1
source share

Hosting your try-catch has nothing to do with the performance of your application. Even if this were so, it would be completely insignificant, which is not where you want to direct your energy. Perform based on needs first, and then optimize. Do not micro-optimize.

0
source share

Can you break from the outside? I do not think your assumption that 2 are equivalent is true.

My intuition tells me that trying / catching outside the loop is better. If there is an influence of bytecode, by writing a try / catch, a smaller one is better created. If there is no impact, if an exception does not occur, then it does not matter. I see no circumstances where a try / catch attempt inside would be better.

I could be wrong ...

-one
source share

The second example (the try-catch block surrounding the code) is faster and more understandable.

-one
source share

All Articles