I was shocked at how slow DateTime.Parse is.
This code takes around 100 seconds to run; if I use regex version it takes 100 milliseconds.
What is going on here?
Stopwatch sw = new Stopwatch();
sw.Start();
var re = new Regex(@"(\d\d)/(\d\d)/(\d\d\d\d) (\d\d):(\d\d):(\d\d)", RegexOptions.Compiled);
for (int i = 0; i < 100000; i++)
{
//var m = re.Match("08/01/2012 23:10:12");
DateTime.Parse("08/01/2012 23:10:12", CultureInfo.CreateSpecificCulture("en-US"));
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Edit: Mark is right, moving the CultureInfo.CreateSpecificCulture("en-US") outside the loop helped. The reason I didn’t do it before is that I profiled this code with VS Profiler and it showed following result:

It’s not a fair test.
The call to
CultureInfo.CreateSpecificCulture("en-US")is the slow part. Move it outside the loop, store the result and reuse it.Your regular expression only handles one specific format, but
DateTime.Parsecan handle many different input formats. It has to decide which of the many format it understands is the correct one to use. If you know in advance what the format is then useDateTime.ParseExactinstead ofDateTime.Parse.The fixed code is as follows:
With these two changes, I get that the
DateTime.ParseExactand the regular expression approach are almost the same.And your regular expression accepts some datetimes that are invalid, such as
00/00/0000 99:99:99. If you fix it so that it only accepts valid datetimes it would be slower.