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?
In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.
Still, there are some situations where the existence of a try/catch block may prevent optimizations which--but for the try/catch--would have allowed code to run faster. Save this answer. Show activity on this post. Yes, try/catch will "hurt" performance (everything is relative).
This answer will obviously vary from compiler to compiler and application to application, but generally yes — “try and catch” is slower than some of the other canonical alternatives to error handling.
First and foremost, remember that using try and catch doesn't actually decrease performance unless an exception is thrown. It's "zero cost" exception handling – no instruction related to exception handling is executed until one is thrown.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With