C ++中的异常真的很慢 [英] Are Exceptions in C++ really slow
问题描述
我正在观看 C ++中的系统错误处理 - Andrei Alexandrescu < a>他声称 C ++中的异常
非常慢。
我想知道的是, C ++ 98
Itanium ABI,VC ++ 64位)是零成本模型异常。
这个想法是,不是通过设置一个保护并显式检查存在异常到处,编译器生成一个侧表,将任何可能抛出异常的点(程序计数器)映射到处理程序列表。当抛出异常时,请参考这个列表来选择合适的处理程序(如果有的话)和堆栈是否解开。
与典型的 if (错误)
策略:
- 零成本模型顾名思义,发生异常时
- 它花费大约10x / 20x和
if
。
- 确定正确的处理程序涉及RTTI:许多RTTI描述符,分散在内存和复杂操作(基本上每个处理程序都有
dynamic_cast
测试)
但是,费用并不是很重要:
,因此从内存中提取需要很长时间。缓存缺失,因此与纯CPU代码相比并不简单。
注:有关更多详细信息,请阅读 TR18015报告,第5.4章异常处理(pdf)
所以,是的,异常在异常路径上缓慢,但是它们通常比显式检查( 注意:根据NoSenseEtAl,Andrei Alexandrescu似乎质疑这个更快。我个人测量了我的程序的加速,我还没有看到有关优化失败的证明。 这很重要吗? 我会声称没有。程序应以可读性,而不是性能(至少,不作为第一个标准)编写。当期望调用者不能或不希望现场处理故障并将其传递到堆栈时,将使用异常。 这是微妙的,但我声称 I was watching Systematic Error Handling in C++—Andrei Alexandrescu he claims that I want to know is this still true for The main model used today for exceptions (Itanium ABI, VC++ 64 bits) is the Zero-Cost model exceptions. The idea is that instead of losing time by setting up a guard and explicitly checking for the presence of exceptions everywhere, the compiler generates a side table that maps any point that may throw an exception (Program Counter) to the a list of handlers. When an exception is thrown, this list is consulted to pick the right handler (if any) and stack is unwound. Compared to the typical The cost, however, is not trivial to measure: so, mostly cache misses, and thus not trivial compared to pure CPU code. Note: for more details, read the TR18015 report, chapter 5.4 Exception Handling (pdf) So, yes, exceptions are slow on the exceptional path, but they are otherwise quicker than explicit checks ( Note: according to NoSenseEtAl, Andrei Alexandrescu seems to question this "quicker". I personally measured a speed-up in my programs and I have yet to see a proof about the loss of optimizability. Does it matter ? I would claim it does not. A program should be written with readability in mind, not performance (at least, no as first criterion). Exceptions are to be used when one expects that the caller cannot or will not wish to handle the failure on the spot, and pass it up the stack. Bonus: in C++11 exceptions can be marshalled between threads using the Standard Library. This is subtle though, I claim that 这篇关于C ++中的异常真的很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!如果
策略)更快。 / p>
map :: find
不应该抛出但是我很好用 map :: find
返回 checked_ptr
如果尝试取消引用它会失败,因为它是null:在后一种情况下,如在Alexandrescu介绍的类的情况下,调用者选择之间显式检查和依赖关于例外。赋予呼叫者权力而不给予他更多的责任通常是良好设计的标志。Exceptions in C++
are very very slow.C++98
if (error)
strategy:
if
when an exception does occur
dynamic_cast
test for each handler)if
strategy) in general.
map::find
should not throw but I am fine with map::find
returning a checked_ptr
which throws if an attempt to dereference it fail because it's null: in the latter case, as in the case of the class that Alexandrescu introduced, the caller chooses between explicit check and relying on exceptions. Empowering the caller without giving him more responsibility is usually a sign of good design.