c# - 抛出异常时 try catch 性能问题

标签 c# performance try-catch

<分区>

我刚刚看到一段看起来很像这样的代码:

    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 的工作原理,但没有找到任何可以澄清我的问题的内容

最佳答案

关于c# - 抛出异常时 try catch 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41636458/

相关文章:

c# - Metro应用直接关注我的第一个领域

c# - 防止使用过期密码打开 ODP.net 连接

c# - 将按键事件绑定(bind)到 WPF 中的 ListViewItem

node.js - Sequelize- Try block 不会捕获 model.create() 错误

c# - 这个 try-catch block 有效吗?

c# - Entity Framework 、依赖注入(inject)和共享对象

sql - SSIS 预评估阶段需要很长时间

java - 替代 long 以避免斐波那契数列溢出

javascript - 跳出嵌套循环 : return or label/break?

java - 使用 catch 分配一个新的整数值