尝试/捕获最佳实践以获得最佳性能 [英] try/catch best practices for optimal performance
问题描述
我听说try / catch被认为对性能不利,但是如果你很少期待抛出异常,那么它们被认为是返回失败信息的一种更好的方式,而不是使用布尔值的方法/函数
I've heard that try/catches are considered to be bad for performance, but that if you're rarely expecting to throw exceptions then they are considered a better way to return failure information rather than using methods/functions with Boolean values.
以这种方式使用try / catch更好或更差的性能?
Does using try/catch in this manner better or worse for performance? It certainly makes coding easier.
例如:
void DoSomething(){
try{
DoSomethingIffy();
} catch {
// Yikes! Do failure stuff
}
}
void DoSomethingIffy(){
if (rareCondition) {
throw new Exception("oops");
}
}
vs
void DoSomething(){
if (!DoSomethingIffy()) {
// Yikes! Do failure stuff
}
}
bool DoSomethingIffy(){
if (rareCondition) {
return false;
}
else {
return true;
}
}
推荐答案
您看到或期望每秒钟的投注率超过100次,那么它可能会产生性能影响。 (请参阅.NET Framework设计指南:异常投掷)在这种情况下将有利于使用避免在代码的热部分中引发异常的设计。
If you are seeing or expect to see throw rates greater than 100 per second then it will likely have a performance impact. (See .NET Framework Design Guidelines: Exception Throwing) In this case it would be beneficial to use a design that avoids throwing exceptions in "hot" parts of the code.
考虑到,如果这是代码的性能关键部分,则可以输入1,000,000次,1,000次的投掷概率可能是罕见的,但可能会导致性能下降不可接受。
Consider that if this a performance critical section of your code you may enter it 1,000,000 times a second and a throw probability of 1 in 1,000 may be "rare" but it may result in a unacceptable decrease in performance.
你真的要测量这些东西对于现实的用户场景,并从性能角度收集数据以了解一个设计或另一个设计是否会更好(或值得实施更复杂的设计)。
You really have to measure these things for realistic user scenarios and gather data to know if one design or another is going to better (or worth implementing a more complex design) from a performance perspective.
数据,.NET提供与例外专门相关的性能计数器,可以是面对性能问题时的有用诊断。
In terms of data, .NET provides performance counters specifically related to the exceptions which can be a helpful diagnostic when faced with performance issues.
这篇关于尝试/捕获最佳实践以获得最佳性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!