9

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?
ildjarn
  • 62,044
  • 9
  • 127
  • 211
talles
  • 14,356
  • 8
  • 45
  • 58
  • The *compiler* will not optimize anything based on `noexcept`. Only your *code* can optimize things, by forcing the compiler to pick between different functions based on whether `noexcept` is available or not. – Nicol Bolas Mar 17 '13 at 07:35
  • @NicolBolas I know that the purpose of using noexcept is not for optimization. But searching around, I found mixed answers in this area ([like this one](http://stackoverflow.com/q/10787766/1316620)), it is still unclear to me what exactly can (or should) be optmized by the compiler or even if it is to early to tell. – talles Mar 17 '13 at 13:05

1 Answers1

11

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.

mirk
  • 5,302
  • 3
  • 32
  • 49