ASP.NET performance: which is faster?

三世轮回 提交于 2019-12-25 18:33:41

问题


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.


回答1:


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.




回答2:


Reading something once versus twice will be faster.

That does not necessarily mean better though.




回答3:


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.



来源:https://stackoverflow.com/questions/18064332/asp-net-performance-which-is-faster

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!