2015-10-27 118 views
0

我从我的数据库查询并为表中的每一行执行以下功能。我有大约400,000行。DateTimeOffset.Parse的性能下降吗?

当我使用VS内置工具分析性能时,似乎DateTimeOffset.Parse花费了大量时间。具有不同类型的其他属性(例如string,int,bool)所需的数量要少得多。

有没有一种方法来优化DateTimeOffset.Parse的性能?

private MyItem GetMyItemData() 
    { 
     var entity = new MyItem(); 

     //**** Lots of setting other entity properties**** 

     entity.ActiveDate = 
      string.IsNullOrEmpty(this.DataManager.Reader["ActiveDate"].ToString()) ? 
      DateTimeOffset.MinValue : DateTimeOffset.Parse(this.DataManager.Reader["ActiveDate"].ToString()); 


     return entity; 
    } 

谢谢!

+0

什么格式是'源ActiveDate'场?您正在转换为字符串,然后转换为DateTimeOffset ...是否有更好的转换选项,更直接?例如,如果该字段是'DateTime'(您可以使用'DateTime'进行测试,那么直接将其转换为'DateTimeOffset'比转换为字符串并返回要快得多。 – Corey

+0

感谢Corey,我认为转换选项由同伴提供最好。 – Water

回答

1

如果您知道传入字符串的格式,TryParseExact可能会为您提供更好的性能。

不同功能的比较:DateTime parsing performance

你应该写一些测试你的自我验证这一点对于的DateTimeOffset。

你两次这样做,这是一个大的数据结构也许昂贵:

this.DataManager.Reader["ActiveDate"].ToString() 

rewite它:

string activedatestr = this.DataManager.Reader["ActiveDate"].ToString(); 
entity.ActiveDate = 
     string.IsNullOrEmpty(activedatestr) ? 
     DateTimeOffset.MinValue : DateTimeOffset.**Parse**(activedatestr); 
+0

感谢同行,TryParseExact帮助减少了时间。 – Water