try-catch块是否降低性能 [英] Does try-catch block decrease performance

查看:216
本文介绍了try-catch块是否降低性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接指出,


要捕获异常,我们必须将一部分代码放在异常
检查下。这是通过在try
块中包含该部分代码来完成的。当该块中出现异常情况时,抛出一个
异常,将控件转移到异常
处理程序。如果没有异常抛出,代码继续正常,
将忽略所有处理程序。


这是否意味着尝试

解决方案

TL; DR NO ,与错误代码处理相比,异常通常比非特殊路径更快。






嗯,明显的说法是比较什么?



与不处理错误相比,显然降低了性能;但性能是否缺乏正确性?我会认为它不是,所以让我们假设你的意思是与一个如果语句检查的错误代码相比。



在这种情况下,这取决于。有多种机制用于实现异常。实际上,他们可以用一个机制实现,如果 c $ c>如果表示他们最终具有相同的成本(或略高)。


在C ++中,所有主要的编译器(gcc在4.x系列中引入了它,MSVC将其用于64位代码)现在使用零成本异常模型。如果您阅读了关于Need4Sleep的技术论文,它被列为表驱动的方法。这个想法是,对于程序的每个点,可能会抛出您在一个边表中注册一些位和块,这将允许您找到正确的catch子句。老实说,与旧的策略相比,它的执行速度比较复杂,但是,零成本名称是由于免费的事实是不会引起异常的。对比一下CPU上的分支错误预测。另一方面,当抛出异常时,惩罚是巨大的,因为表存储在冷区中(因此可能需要往返RAM或更差)...但异常总结一下,现代C ++编译器的异常比错误代码要快,代价较大的二进制(由于静态表)。



/ p>

This link states,

To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.

Does it mean that having a try block reduces performance due to the extra task of "inspection" during run time?

解决方案

TL;DR NO, exceptions are usually faster on the non-exceptional path compared to error code handling.


Well, the obvious remark is compared to what ?

Compared to not handling the error, it obviously decrease performance; but is performance worth the lack of correctness ? I would argue it is not, so let us supposed that you meant compared to an error code checked with an if statement.

In this case, it depends. There are multiple mechanisms used to implement exceptions. Actually, they can be implemented with a mechanism so close to an if statement that they end up having the same cost (or slightly higher).

In C++ though, all major compilers (gcc introduced it in 4.x serie, MSVC uses it for 64 bits code) now use the Zero-Cost Exception Model. If you read this technical paper that Need4Sleep linked to, it is listed as the table-driven approach. The idea is that for each point of the program that may throw you register in a side-table some bits and pieces that will allow you to find the right catch clause. Honestly, it is a tad more complicated implementation-wise than the older strategies, however the Zero Cost name is derived by the fact that it is free should no exception be thrown. Contrast this to a branch misprediction on a CPU. On the other hand, when an exception is thrown, then the penalty is huge because the table is stored in a cold zone (so likely requires a round-trip to RAM or worse)... but exceptions are exceptional, right ?

To sum up, with modern C++ compilers exceptions are faster than error codes, at the cost of larger binaries (due to the static tables).

这篇关于try-catch块是否降低性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆