我有一个方法可以检查传入的异常并返回一个 bool 值。
目前我的实现是这样的
private bool ExceptionShouldNotify(Exception e)
{
return
e is FirstCustomException ||
e is SecondCustomException ||
e is ThirdCustomException ||
e is FourthCustomException ||
e is FifthCustomException ||
e is SixthCustomException ||
e is SeventhCustomException;
}
然而,使用字典查找比多个 OR
语句和 is
检查在性能方面更好吗?
像这样:
private bool ExceptionShouldNotify(Exception e)
{
var dict = new Dictionary<String, int> {
{ "FirstCustomException", 1 },
{ "SecondCustomException", 1 },
{ "ThirdCustomException", 1 },
{ "FourthCustomException", 1 },
{ "FifthCustomException", 1 },
{ "SixthCustomException", 1 },
{ "SeventhCustomException", 1 }
};
return dict.ContainsKey(e.GetType().Name);
}
最佳答案
硬编码(第一种解决方案)是一种不好的做法,这就是我投票支持字典(第二种解决方案)的原因,但我建议采用不同的实现方式:
// HashSet - you don't use Value in the Dictionary, but Key
// Type - we compare types, not their names
private static HashSet<Type> s_ExceptionsToNotify = new HashSet<Type>() {
typeof(FirstCustomException),
typeof(SecondCustomException),
...
};
// static: you don't use "this" in the method
private static bool ExceptionShouldNotify(Exception e) {
return s_ExceptionsToNotify.Contains(e.GetType());
}
捕获异常(包括堆栈跟踪)你已经有很大的开销;这就是为什么性能(7 个简单比较与计算哈希)不是上下文中的主要问题
关于c# - 检查异常类型性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41140736/