在 try-catch 块中包装循环会导致性能问题吗?

Could wrapping a loop in a try-catch block cause performance problems?

在使用无限循环的游戏或其他应用程序中,将循环包装在 try-catch 块中是否会影响性能?

像这样:

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();
}

我标记了 gcc,但任何其他编译器也适用。

好吧,将循环包装在 try {} catch() {} 块中,会在进入 try {} 块时给您带来较小的性能影响,但不会影响循环中各个迭代的执行。

比。一个非包装版本,进入 try { } 块需要编译器发出一些额外的指令才能进入定义的 catch() {} 块。这些额外的指令与展开的循环相比会有(非常小的)性能差异。

甚至,如果 try {} catch() {} 将应用于循环的内部部分,安装 catch() {} 块入口点的开销将只应用一次,而不是用于单独的迭代。