Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

noexcept specifier and compiler optimizations

I have read unclear things regarding the noexcept specifier and compiler optimizations. When specifying noexcept the compiler may optimize:

  • Compile time (faster compilation).
  • Execution time (code runs faster).
  • Or both?
  • Or none?
like image 330
talles Avatar asked Mar 17 '13 04:03

talles


People also ask

Does Noexcept make code faster?

Declaring a function noexcept helps optimizers by reducing the number of alternative execution paths. It also speeds up the exit after failure. The keyword noexcept serves two purposes (like most of the language, really): It's an instruction to the compiler, and it's also helpful to humans who are reading the code.

What is the purpose of Noexcept?

The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.

When should you use Noexcept C++?

The dynamic exception specification, or throw(optional_type_list) specification, was deprecated in C++11 and removed in C++17, except for throw() , which is an alias for noexcept(true) . We recommended you apply noexcept to any function that never allows an exception to propagate up the call stack.

What happens when Noexcept function throws?

Note that noexcept doesn't actually prevent the function from throwing exceptions or calling other functions that are potentially throwing. Rather, when an exception is thrown, if an exception exits a noexcept function, std::terminate will be called.


1 Answers

The original reason for noexpect was to enable libraries to use faster move-constructors internally, if the calling function is not allowed to throw by specification.

Next, big performance optimizations can be achieved in containers like STL vector when your type’s move constructor and move assignment are annotated with noexcept. When STL utility std::move_if_noexcept detects that your moves do not throw it will use these safe moves rather than copies for some operations (like resize). This, in case of containers storing millions of elements, will enable huge optimizations.

(quoted from using-noexcept)


Additionally, the compiler does not have to generate extra code for stack-unwinding, if it knows that no exceptions can be thrown due to a noexpect specifier.


I can't see how compile-time is substantially impacted by noexcept-specifiers. The resulting runtime can be a lot faster though.

like image 119
mirk Avatar answered Oct 26 '22 13:10

mirk