Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are exceptions detrimental to performance?

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.

like image 823
Aequitas Avatar asked Aug 05 '15 23:08

Aequitas


People also ask

What are the performance effects of exceptions?

In this tutorial, we analyzed the performance effects of exceptions. Specifically, it found out the performance cost is mostly in the addition of the stack trace to the exception. If this stack trace is unwound afterward, the overhead becomes much larger.

Why are exceptions so expensive to handle?

Specifically, it found out the performance cost is mostly in the addition of the stack trace to the exception. If this stack trace is unwound afterward, the overhead becomes much larger. Since throwing and handling exceptions is expensive, we shouldn't use it for normal program flows.

Why should we avoid throwing exceptions?

Thank you. One common concern related to exceptions is that if exceptions are used for code that routinely fails, the performance of the implementation will be unacceptable. This is a valid concern. When a member throws an exception, its performance can be orders of magnitude slower.

Are exceptions too expensive in Java flow control?

Overview In Java, exceptions are generally considered expensive and shouldn't be used for flow control. This tutorial will prove that this perception is correct and pinpoint what causes the performance issue. 2. Setting Up Environment Before writing code to evaluate the performance cost, we need to set up a benchmarking environment. 2.1.


1 Answers

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.

like image 113
chrylis -cautiouslyoptimistic- Avatar answered Oct 13 '22 18:10

chrylis -cautiouslyoptimistic-