【问题标题】:Try Catch performance issues when exception is thrown [duplicate]抛出异常时尝试捕获性能问题[重复]
【发布时间】:2017-01-13 14:09:32
【问题描述】:

我刚刚发现了一个看起来很像这样的代码:

    public static string GetXmlAttributeValue(XmlNode Node, string attributeName, string defVal)
    {
        try
        {
            return Node.Attributes.GetNamedItem(attributeName).Value;
        }
        catch(Exception)
        {
            return defVal;
        }
    }

该方法的思想是尝试获取节点的属性,如果没有则返回默认值。将代码更改为以下内容后:

    public static string GetXmlAttributeValue(XmlNode Node, string attributeName, string defVal)
    {
        if(Node.Attributes.GetNamedItem(attributeName) != null)
            return Node.Attributes.GetNamedItem(attributeName).Value;
        return defVal;
    }

我看到了性能的显着提升。更准确地说,在对这个函数的大约 5000 次调用中,第一个实现大约需要 2 秒,而第二个实现几乎是即时的(我需要提到属性不存在的概率非常高,所以会发生很多捕获)。

我的问题是为什么会发生这种情况?我用谷歌搜索了 try catch 的工作原理,但没有找到任何可以澄清我的问题的东西

【问题讨论】:

  • 异常包含一个 StackTrace,走栈来构建这个跟踪是相当昂贵的
  • 并且将控制权传输到catch块所需的设置也不是免费的。
  • 第二种方法甚至可以改进,因为您调用了两次Node.Attributes.GetNamedItem(attributeName)var item = Node.Attributes.GetNamedItem(attributeName); return item?.Value ?? defVal;
  • 正如名称已经让我们假设异常是异常的,所以可以说它不常见。如果您经常遇到这种行为,它是否仍然异常?
  • 产生这种开销的原因很简单,就是创建一个Exception-object 需要一些工作(例如构建堆栈跟踪)——如果重复完成——会产生一些性能损失。

标签: c# performance try-catch


【解决方案1】:

简短回答:使用异常作为流控制会影响性能。

引用 MSDN 关于该主题的内容:Throwing exceptions can negatively impact performance. For code that routinely fails, you can use design patterns to minimize performance issues.

【讨论】:

    猜你喜欢
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多