I parse a string in DateTime millions of times:
public static CultureInfo ci = CultureInfo.InvariantCulture;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
string[] fields = line.Split(' ');
DateTime newDT = DateTime.ParseExact(fields[0], "yyyyMMddTHHmmssfff", ci);
}
My profiler allocates ParseExact as a huge part of the time. Is there another method / approach that could parse a string in a DateTime that would be faster?
FOLLOW UP1:
1) I tried this, but the speed was the same
bool OK = DateTime.TryParseExact(fields[0], "yyyyMMddTHHmmssfff", null, System.Globalization.DateTimeStyles.None,out DT);
2)
I tried to encode my own parser, but it was just as slow too:
public static DateTime fastParse(ref string s)
{
return new DateTime(int.Parse(s.Substring(0,4)), int.Parse(s.Substring(4,2)),int.Parse(s.Substring(6,2)), int.Parse(s.Substring(9,2)),int.Parse(s.Substring(11,2)),int.Parse(s.Substring(13,2)),int.Parse(s.Substring(15, 3)));
}
FOLLOW UP2
I tried Master117 to suggest storing values - AGAIN NO FASTER - perhaps a design problem?
public class fastParseData
{
int year;
int mon;
int day;
int hour;
int min;
string previousSlice = "";
public DateTime fastParse(ref string s)
{
if (previousSlice != s.Substring(0, 12))
{
year=int.Parse(s.Substring(0,4));
mon=int.Parse(s.Substring(4,2));
day=int.Parse(s.Substring(6,2));
hour= int.Parse(s.Substring(9,2));
min = int.Parse(s.Substring(11,2));
previousSlice = s.Substring(0, 12);
}
return new DateTime(year, mon, day, hour,min, int.Parse(s.Substring(13, 2)), int.Parse(s.Substring(15, 3)));
}
}
FOLOW UP3
public class fastParseData
{
int year;
int mon;
int day;
int hour;
int min;
string previousSlice = "";
DateTime previousDT;
public DateTime fastParse(ref string s)
{
if (previousSlice != s.Substring(0, 12))
{
year=int.Parse(s.Substring(0,4));
mon=int.Parse(s.Substring(4,2));
day=int.Parse(s.Substring(6,2));
hour= int.Parse(s.Substring(9,2));
min = int.Parse(s.Substring(11,2));
previousSlice = s.Substring(0, 12);
previousDT = new DateTime(year, mon, day, hour,min,0,0);
}
return previousDT.AddMilliseconds((int.Parse(s.Substring(13, 2))*1000)+int.Parse(s.Substring(15, 3)));
}
}
FOLLOW UP4
From my profiler it seems like a problem
int.Parse(s.Substring(13, 2))
If the Parse bit is more expensive than the substring.
I tried
int.TryParse(s.Substring(13, 2),NumberStyles.None,ci, out secs)
Convert.ToInt32(s.Substring(13, 2));
but again - no difference in speed.
Is there a faster way to parse int?