0

In a game or some other application where an infinite loop would be used, could wrapping the loop in a try-catch block be a detriment to performance?

Something like this:

auto main() -> int{
    game::init();

    try{
        while(1){
            some_func();
            some_other_func();

            if(breaking_func())
                break;

            something_that_could_throw(); // unlikely, though

            draw();
            swap_buffers();
        }
    }
    catch(const std::exception &err){
        // do error handling
    }

    game::cleanup();
}

I tagged gcc, but any other compilers would also be applicable.

RamblingMad
  • 5,332
  • 2
  • 24
  • 48

1 Answers1

1

Well, wrapping the loop in a try {} catch() {} block, will give you a small performance hit when the try {} block is entered, but not for execution of the individual iterations in the loop.

Vs. a non wrapped version, entering the try { } block requires the compiler to emit some additional instructions to be able entering the defined catch() {} blocks coming after. These additional instructions will have a (very small) performance difference vs. an unwrapped loop.

Even, if the try {} catch() {} would be applied to the inner part of the loop, the overhead for installing the catch() {} block entry points will be applied only once, and not for individual iterations.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190