C# 实时 Try Catch

发布于 2024-08-02 18:43:41 字数 288 浏览 10 评论 0原文

我希望得到真正使用 C# 进行实时编程或真正了解该语言内部原理的人的回复。

我知道异常不应该用于处理正常处理,而只能用于检测错误情况。关于这个话题有很多讨论。

我想知道仅仅使用 try/catch 块是否会导致运行时间变慢(除非程序必须结束,否则它永远不会捕获异常)。 try/catch 块位于必须重复调用的函数内部。我怀疑只有最小的成本。

成本可以用 CPU 周期或其他任务(与浮点乘法相同的成本)或其他方式来量化吗?

我们在Windows XP下使用Microsoft C#.Net 3.5。

I'd like a response from someone who actually does real-time programming in C# or who really understands the language internals.

I know that exceptions should not be used to handle normal processing, but only to detect error conditions. There is plenty of discussion on that topic.

I'd like to know if there is any run time slow-down from simply having a try/catch block in place (which never catches an exception unless the program will have to end anyway). The try/catch block is inside a function which must be called repeatedly. I suspect there is only minimal cost.

Can the cost be quantified in terms of CPU cycles, or other tasks (same cost as a floating point multiplication), or another way?

We use Microsoft C#.Net 3.5 under windows XP.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

美男兮 2024-08-09 18:43:41

.NET 异常的开销成本非常非常低,除非抛出异常。使用 try/catch 块对性能的影响非常小。我发现即使在非常快、紧密的循环中,对异常处理的到位也几乎没有影响。

然而,.NET 中的异常在抛出时非常昂贵。如果你使用它们,它们往往比许多其他语言对性能产生更大的影响。这是由于在创建异常时收集了完整的堆栈信息等。

这与其他一些语言相反,例如Python,其中异常处理的成本较高,但抛出实际上相当高效。

但是,如果您担心,我建议您分析一下您的日常习惯,并亲自测试一下。这是我在进行大量性能分析后的经验。在您自己的代码库中进行测量是无可替代的。

.NET exceptions have a very, very low overhead cost unless they are thrown. Having a try/catch block in place will have a very minimal performance impact. I have found nearly no impact, even in very fast, tight loops, to having exception handling in place.

However, exceptions in .NET are VERY expensive when they're thrown. They tend to be much high-impact on performance if you throw them than many other languages. This is due to the full stack information gleaned when the exception is created, etc.

This is the opposite behavior to some other languages, such as python, where exception handling has a higher cost, but throwing is actually fairly performant.

However, if you are concerned, I would suggest you profile your routine, and test it yourself. This has been my experience after quite a bit of performance profiling. There is no substitution for measuring in your own codebase.

洒一地阳光 2024-08-09 18:43:41

这里对 try catch 的性能影响进行了很好的讨论和度量。

当异常发生时,try/catch 块是否会损害性能没有被抛出?

Good discussion, with metrics, of performance implications of try catch here.

Do try/catch blocks hurt performance when exceptions are not thrown?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文