Does the placement of a try-catch block affect performance?

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?

Answers


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.


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.


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.


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...


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


Need Your Help

How to find the .NET framework version of a Visual Studio project?

.net version

I have a project in Visual Studio. How can I find out which .NET Framework version it's for?

Scheduled Dynamic Resque Scheduler never launches worker

ruby-on-rails ruby resque resque-scheduler

While using resque-scheduler to set_schedule dynamic cron jobs based on user's input the schedules seem to be set but the worker never actually starts at the set schedule.