-1

I have a choice here. Two opinions:

One is to read an XML file, which is about one page long, twice and try to find out if I can find a certain attribute value and assign it to a string or not. First time is to find out if the attribute exists and not null. Second time to read and assign the value.

If([xmlAttribute]!= null){
  string = xmlAttribute;
}

Two is just read the same XML file once and try to assign the value directly without try to find it first. If failed, it will throw an exception and the catch block will assign the string to null.

try{
  string = [xmlAttribute];
}catch(Exception ex){
  string = null;
}

Which way is faster? Or any better idea? Thanks.

Joey.Lu
  • 125
  • 8

3 Answers3

4

There is a lot of overhead to creating an Exception--details about the method, stack trace, and underlying error is very time-consuming to collect. Using Exceptions as part of expected program logic is poor coding.

Look for a way to check the data without throwing the exception wherever possible.

Garrison Neely
  • 3,238
  • 3
  • 27
  • 39
  • 1
    Exceptions are reserved for exceptional circumstances. – Dustin Kingen Aug 05 '13 at 17:51
  • 1
    Agreed. And I will add that even if the Exception method runs faster in a limited test, it will not scale as well as any code that uses non-exception logic to perform an action. – Garrison Neely Aug 05 '13 at 17:53
  • Excellent answer. I posted something along these lines as an answer before but the person with the chosen answer(using exception throwing!) thought otherwise (and I'm pretty sure he down voted me). http://stackoverflow.com/a/17886280/1132959 Anyway great answer, I agree. – user1132959 Aug 05 '13 at 17:53
0

Reading something once versus twice will be faster.

That does not necessarily mean better though.

Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • 1
    It depends on how often the exception is thrown, if reading once takes 1000x times longer when a exception is thrown you must not throw an exception more than 1 time in 1000 for it to be worth it. – Scott Chamberlain Aug 05 '13 at 17:55
  • Right, but the question states that "if" an exception happens, not an exception happens every time. I do not disagree that exceptions cost a lot though. – Karl Anderson Aug 05 '13 at 17:56
0

Assuming you are using Linq to XML:

var element = xml.Element("Name");
var attribute = element == null ? null : element.Attribute("first");
var value = attribute == null ? null : attribute.Value;

I typically add some extension methods to ease this process, for instance:

var value = xml.Element("Name").OptionalAttribute("first").ValueOrDefault();

How you name the extension methods is up to you.

Guvante
  • 18,775
  • 1
  • 33
  • 64