In what ways do C++ exceptions slow down code when there are no exceptions thown?(当没有抛出异常时,C++ 异常以什么方式减慢代码速度?)
问题描述
我已经读到使用 C++ 异常进行异常处理有一些开销,而不是检查返回值.我只是在谈论没有抛出异常时产生的开销.我还假设您需要实现实际检查返回值并执行适当操作的代码,无论这与 catch 块所做的操作等效.而且,将抛出异常对象的代码与内部包含 45 个状态变量的代码与为每个错误返回负整数的代码进行比较也是不公平的.
I have read that there is some overhead to using C++ exceptions for exception handling as opposed to, say, checking return values. I'm only talking about overhead that is incurred when no exception is thrown. I'm also assuming that you would need to implement the code that actually checks the return value and does the appropriate thing, whatever would be the equivalent to what the catch block would have done. And, it's also not fair to compare code that throws exception objects with 45 state variables inside to code that returns a negative integer for every error.
我并不是仅仅根据可能执行得更快的 C++ 异常来构建一个案例来支持或反对 C++ 异常.我最近听说有人提出,一旦您考虑到检查返回值和处理错误所需的所有额外簿记代码,使用异常的代码应该与基于返回码的代码一样快地运行.我错过了什么?
I'm not trying to build a case for or against C++ exceptions solely based on which one might execute faster. I heard someone make the case recently that code using exceptions ought to run just as fast as code based on return codes, once you take into account all the extra bookkeeping code that would be needed to check the return values and handle the errors. What am I missing?
推荐答案
在 some 平台和 some 编译器上进行异常处理是有成本的.
There is a cost associated with exception handling on some platforms and with some compilers.
也就是说,Visual Studio 在构建 32 位目标时,将在每个具有非平凡析构函数的局部变量的函数中注册一个处理程序.基本上,它设置了一个 try/finally
处理程序.
Namely, Visual Studio, when building a 32-bit target, will register a handler in every function that has local variables with non-trivial destructor. Basically, it sets up a try/finally
handler.
gcc
和面向 64 位的 Visual Studio 采用的另一种技术仅在抛出异常时产生开销(该技术涉及遍历调用堆栈和表抬头).在很少抛出异常的情况下,这实际上可以产生更高效的代码,因为不必处理错误代码.
The other technique, employed by gcc
and Visual Studio targeting 64-bits, only incurs overhead when an exception is thrown (the technique involves traversing the call stack and table lookup). In cases where exceptions are rarely thrown, this can actually lead to a more efficient code, as error codes don't have to be processed.
这篇关于当没有抛出异常时,C++ 异常以什么方式减慢代码速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当没有抛出异常时,C++ 异常以什么方式减慢代码速度?


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30