Reputation: 739
i thought about the fact, that using try and catch is useful to prevent crashes if there are mistakes, but i was curious if there is any impact at the performance if i overuse the try and catch block.
To resume: Is there any impact at the performance if i use try and catch(nearly) everywhere?
Upvotes: 1
Views: 710
Reputation: 49754
Exception throwing/handling does come with a slight performance penalty (the exact amount varies greatly by the exact scenario), but performance shouldn't be your first consideration.
Upvotes: 2
Reputation: 3683
I think the main hit to performance you are going to see (assuming the code in question is executed at a very high frequency) will be from garbage collection.
One trivial example (this you do actually see in production code every now and then ...) would be having password verification logic like:
if (!password.equals(correctPassword)) {
throw new IncorrectPasswordException();
}
and then ...
catch (final IncorrectPasswordException ex) {
//some output or so
}
... instead of simply never throwing anything and just handling this via conditionals. You will eventually have to clean up all those IncorrectPasswordException
from memory.
In this case overusing exceptions actually will become pretty costly by turning simple evaluations into object instantiations that cost you memory and even more importantly eventually cost you precious CPU cycles for reclaiming that memory via garbage collection.
Upvotes: 2