5

See this question where everyone talks about how "obviously" performance will suffer, or exceptions should be avoided when performance is an issue, etc.

But I haven't seen a good explanation as to Why throwing exceptions are bad for performance, everyone in that question seem to take it for granted.

The reason I ask this, is that I'm attempting to optimize an application and have noticed that several hundred exceptions are thrown and swallowed on certain actions, such as clicking a button to load a new page.

Community
  • 1
  • 1
Aequitas
  • 1,875
  • 1
  • 19
  • 43

1 Answers1

5

First, of course, it's simply bad design because "exception" has a semantic meaning ("some circumstance prevented this method from fulfilling its contract"), and that's abusing the feature in a bad-surprise way.

In the case of Java, creating exception objects (specifically, filling in stack traces) is extremely expensive because it involves walking the stack, lots of object allocations and string manipulations, and so on. Actually throwing the exception isn't where the main performance penalty is.

chrylis -cautiouslyoptimistic-
  • 67,584
  • 19
  • 106
  • 140
  • 3
    Not quite so. What object allocations and string manipulations are you talking about? `StackTraceElement`s are created lazily upon `getStackTrace()` call, not on throwing or catching an exception. Furthermore, hot implicit exceptions (like NullPointerException, ClassCastException, ArrayIndexOutOfBoundsException etc) do not even require stack walking - they are as fast as `goto`. – apangin Aug 05 '15 at 23:57