I just came over a code that looks pretty much like this:
public static string GetXmlAttributeValue(XmlNode Node, string attributeName, string defVal)
{
try
{
return Node.Attributes.GetNamedItem(attributeName).Value;
}
catch(Exception)
{
return defVal;
}
}
The ideea of this method is to try to get a node's attribute and return a default value if it has none. After changing the code to something like this:
public static string GetXmlAttributeValue(XmlNode Node, string attributeName, string defVal)
{
if(Node.Attributes.GetNamedItem(attributeName) != null)
return Node.Attributes.GetNamedItem(attributeName).Value;
return defVal;
}
I saw a drastic improvement in performance. To be a little more exact, on about 5000 calls to this function, the first implementation took about 2 seconds, while the second implementation is pretty much instant (i need to mention that the probability of the attribute not to exist is pretty high, so a lot of catch-es will occur).
My question is why does this happen? I google-ed how try catch works, but haven't found anything that could clarify my question