c# - 检查异常类型性能

标签 c# performance exception

我有一个方法可以检查传入的异常并返回一个 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/

相关文章:

java - 衡量 Java 应用程序的性能

javascript - 在它变得粗鲁之前有多少内存?

c++ - 如何在没有OOM killer 的情况下发出C++终止捕获

c# - 缩进多行文本

Java\jdk1.7.0_06\bin\java.exe'' 以非零退出值 1 android studio 完成

c# - Revit,如何获取选定墙的位置、长度和高度

c# - 使用 DDD 和 Azure 进行优雅的异常处理

exception - 在 Dart 中管理登录/功能错误的最佳做法是什么?

c# - 我如何告诉 Resharper ICollectionView 包含的类型?

c# - 高效搜索树结构中的所有节点