Exceptions cause performance problem?

6

When working on an application whose performance is important, we recommend NOT USE exceptions . With this comes the question " what makes exceptions so much 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 does noexcept have on a function?

    
asked by anonymous 03.10.2018 / 14:33

1 answer

6

In fact it even avoids using exception in C ++ because neither is something so standardized. They are even thinking of something and perhaps in C ++ 23 it has a new exception mechanism that is more useful and standardized, in addition to having zero cost in most of the scenarios.

The exception mechanism can be implemented in many ways and nothing in the language specification requires one form or another or a performance guarantee, and this in itself is already 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 check if something has been thrown (the release is placed somewhere in memory that < in> branch knows)
  • Stacking the exception and jumping at the end of the routine so that the exception throw knows where to go
  • has a complex and sophisticated compiler-aided mechanism that increases application size and memory allocation and needs and a slow algorithm to figure out where to go in launch

The first two are cost even if the exception is not thrown, which can be pretty bad when it's usually not supposed to happen, it's the cases where the exception should be used. So decent implementations of C ++ do not choose it.

The non-cost way forced the release to have an absurdly higher cost to make the attempt. It may seem simple and naive to throw an exception, but a lot happens in your trigger. And if you do not expect this is pretty bad.

Another point, and perhaps this is 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 can also occur because of templates ), which usually gives a big gain in the call in many cases and allows other optimizations, even the library works best with is guaranteed that it is not operating on something that throws exception.

The noexcept creates a contract that tells the compiler that there is no exception in it. Being a contract if it changes in the future is a breach of compatibility. Without this it would be very easy to change the implementation and place an exception without any noticeable differences.

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

    
03.10.2018 / 15:18