为什么抛出异常这么慢?抛出、异常

2023-09-05 03:54:11 作者:梦幻星空つ

他们告诉我们不要使用异常流量控制我们的节目,因为抛出异常缓慢。我从来没有听说过为什么抛出异常这么慢任何解释。

They are telling us not to use exceptions to control flow of our programs because throwing exceptions is slow. I have never heard any explanation why is throwing exceptions so slow.

所以,问题是:

什么是抛出异常的机制,什么是涉及的特定操作可能有性能影响?

What is the mechanism of throwing exceptions and what are particular operations involved which may have performance impact?

编辑:

一些澄清:我想听到什么额外的工作是由操作系统需要处理抛出异常。有用户和内核模式之间切换的设置这是昂贵的?或者,也许构造异常对象是昂贵吗?或者,也许有一些与切换程序流程,我缺少的是什么?我的问题是编程语言无关的(我希望如此,但证明我错了)。但是如果你需要一些锚点,然后我的兴趣是最符合这个主题相关的.NET内部。

Some clarification: I would like to hear what extra work is need by operation system to handle throwing exceptions. Is there some switching between user and kernel mode which are that costly? Or maybe constructing exception object is costly? Or maybe there is something with switching program flow what I am missing? My question is programming language agnostic (I hope so, but prove me wrong). However If you need some anchor then I am interest the most in .NET internals related with this topic.

EDIT2:

我没有与例外的业绩有关的问题。我只是想了解这种机制的内部。

I don't have any issues with exceptions performance. I just would like to understand internals of this mechanism.

EDIT3:

使我的问题更清楚。

推荐答案

异常处理需要一定的复杂性和神奇。借调@乔尼的反应的主要成本就是收集堆栈跟踪。当一个异常被抛出,运行时间已经走在协议栈的活动记录寻找一个兼容的异常处理程序,执行finally块中的每一步。所有这一切都发生在运行时间;它不能被编译器固定起来。在像C ++语言的析构函数必须执行。

Exception handling requires some complexity and "magic". Seconding @Joni's response a major cost is gathering the stack trace. When an exception is thrown, the run time has to walk down the stack's activation records looking for a compatible exception handler, executing finally blocks each step of the way. All this has to occur at run time; it can't be fixed up by the compiler. In languages like C++ destructors have to be executed.

异常处理本质上是一个带外特殊处理模式。事情加快正常执行,例如缓存不正常工作。 (我会想象局部性的引用是差了很多在这里)。该处理可以优化,但由于EXC移交被认为是特殊它给较少注意。

Exception processing is essentially an out of band "exceptional" processing mode. Things that speed up normal execution such as caching don't work as well. (I would imagine locality-of-reference is a lot worse here). This processing could be optimized, but since exc handing is supposed to be "special" it's given less attention.