我有一个方法来检查传入的异常并返回一个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' –
当你处于故障路径时,你真的关心性能吗?你是否期望你的客户说:“好吧,它倒下了,但它真的*快!” –