Reputation: 109
Does the placement of a try-catch block affect performance?
EXAMPLE 1: try-catch block inside of the while-loop
while (true) {
try {
// ... read from a file
} catch (EOFException e) {
break;
}
}
EXAMPLE 2: try-catch block surrounds the while-loop
try {
while (true) {
// ... read from a file
}
} catch (EOFException e) {
// :P
}
Logically, these two examples are equivalent, but which should I prefer?
Upvotes: 7
Views: 2800
Reputation:
The placement of your try-catch has no incidence whatsoever on the performance of your application. Even if it did, it would be completely negligible, that's not where you want to direct your energy. Implement based on need first, and then optimize. Don't micro-optimize.
Upvotes: 0
Reputation: 109
The second example (try-catch block surrounding the code) is both faster and clearer.
Upvotes: -1
Reputation: 1577
Should java try blocks be scoped as tightly as possible?
This gives a much better answer than I could. Short of it is, they only add an entry onto a table that's checked when exceptions are thrown, so unless an exception is thrown they don't affect performance. It'd be best to just put it wherever makes it best to try recover, if you can. If not, wherever's useful or makes sense. Though with break outside the loop, I don't think the second is valid anyway.
Upvotes: 4
Reputation: 120198
can you break from outside the while? I don't think your presupposition, that the 2 are equivalent are true.
My intuition tells me that the try/catch outside the loop is better. If there is a bytecode impact by writing a try/catch, having less created is better. If there is no impact unless the exception occurs, then it doesn't matter. I don't see any circumstances where having the try/catch inside would be better.
I could be wrong...
Upvotes: -1
Reputation:
Whatever overhead try-catch
incurs is probably negligible, but what draws my attention more with the first case is that it's misleading: you're catching an exception, only to abort the loop. I'd pick solution 2 just because it's consistent with the intent. And you avoid any overhead that way.
Upvotes: 2