Search code examples
c++boostc++11

Does noexcept improve performance?


Is the noexcept function specifier aimed to improving the performance because of potentially no book-keeping code for exceptions in the generated object, and therefore should be added to function declarations and definitions whenever possible? I think of wrappers for callable objects in the first place, where noexcept could make some difference, although the checking expressions might "bloat" the source code. Is it worth?


Solution

  • Top compilers produce code that is already optimized a lot like code that can't throw, and then the case when an exception occurs is handled by out-of-line code that the exception-handling mechanism finds by looking at meta-data concerning the function. I suppose there's some benefit in code size to omitting this when it's known not to be needed, though.

    There are probably some cases where a nothrow specification does allow some specific optimization:

    int main() {
        int i = 0;
        try {
            ++i;
            thing_that_cannot_throw();
            ++i;
            thing_that_can_throw();
            ++i;
        } catch (...) {}
        std::cout << i << "\n";
    }
    

    Here the second ++i could in theory be reordered before the call to thing_that_cannot_throw (and i just initialized to 2). Whether it is in practice is another matter, though, since an implementation that makes guarantees about the state of variables in the debugger or in the stack above a function call, would want i to have value 1 during that call even though it's a local variable not observable by any standard means.

    I suspect that nothrow guarantees are more valuable to the programmer than to the compiler. If you're writing code that offers the strong exception guarantee then usually there will be certain critical operations you perform, that you need to offer the nothrow guarantee (swaps, moves and destructors being the common candidates).