Do exceptions cause problems for performance?

Asked

Viewed 62 times

8

When working in an application whose performance is important, NO USE of exceptions. With this comes doubt "what makes the exceptions so bad for performance?"

In practical terms what is the need to use noexcept in a function? That is, at the end of the day, what impact noexcept has a function?

1 answer

8


In fact, you avoid using a C++ exception because it’s not even that standardized. They are even thinking about something and maybe C++23 has a new exception mechanism that is more useful and standardized, besides having zero cost in most scenarios.

The exception mechanism can be implemented in many ways and nothing in the language specification requires a form or other or a guarantee of performance, and that alone is a problem for a language like C++.

In general an exception ends:

  • putting a branch, that is, a kind of if somewhere without you noticing, so checks if something was released (the release is placed somewhere in memory that this branch knows)
  • Stacking the exception and popping at the end of the routine so the exception launch knows where to go
  • has a complex and sophisticated compiler-aided mechanism that increases application size and memory occupation and accurate and a slow algorithm to figure out where you need to go at launch.

The first two have cost even if the exception is not cast, which can be very bad when it is not usually meant to happen, are the cases where the exception should be used. That’s why decent C++ implementations don’t opt for it.

The form without cost obliged the launch have an absurdly higher cost to realize the intent. It may seem simple and naive to make an exception, but there is a lot going on in your drive. And if you don’t expect it, it’s pretty bad.

Another point, and maybe that’s what you’re wondering, is that the fact that a function throws an exception makes it difficult or impossible optimize the function by inline (which may also occur because of templates), that usually gives a big gain on the call in many cases and allows other optimizations, even the library works better with is guaranteed that it is not operating on something that generates exception.

The noexcept creates a contract that indicates to the compiler that there is no exception in it. Because it is a contract to change in the future it is a breach of compatibility. Without this it would be very easy to change the implementation and put an exception without greater noticeable differences.

It is true that in many cases the optimizations can happen even without it, but the use gives a better guarantee, and allows a greater readability of the intention of what did there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.