C# 中“尝试"的性能成本 [英] Performance Cost Of 'try' in C#
问题描述
我知道异常会降低性能,并且尝试和避免异常通常比在所有内容中删除一个大的 try/catch 更有效——但是 try 块本身呢?即使从未抛出异常,仅声明 try/catch 的成本是多少?
I know that exceptions have a performance penalty, and that it's generally more efficient to try and avoid exceptions than to drop a big try/catch around everything -- but what about the try block itself? What's the cost of merely declaring a try/catch, even if it never throws an exception?
推荐答案
try 的性能开销很小.异常处理的主要成本是获取堆栈跟踪和其他元数据,而在您实际必须抛出异常之前,不会支付这些成本.
The performance cost of try is very small. The major cost of exception handling is getting the stack trace and other metadata, and that's a cost that's not paid until you actually have to throw an exception.
但这会因语言和实现而异.为什么不用 C# 编写一个简单的循环并自己计时?
But this will vary by language and implementation. Why not write a simple loop in C# and time it yourself?
这篇关于C# 中“尝试"的性能成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!