当没有异常时,C++ 异常会以何种方式减慢代码速度?

时间:2023-03-08
本文介绍了当没有异常时,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++ 异常的案例.我听说最近有人提出这样的案例,一旦您考虑到检查返回值和处理错误所需的所有额外簿记代码,使用异常的代码应该与基于返回代码的代码一样快地运行.我错过了什么?

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?

推荐答案

某些 平台和某些 编译器上的异常处理会产生相关成本.

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++ 异常会以何种方式减慢代码速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:为什么要捕获异常作为对 const 的引用? 下一篇:如何在 GDB 中打印 C++ 向量的元素?

相关文章