<分区>
我刚刚看到一段看起来很像这样的代码:
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 的工作原理,但没有找到任何可以澄清我的问题的内容