Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is DateTime.Parse so slow?

Tags:

c#

.net

datetime

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:

enter image description here

like image 481
Andrey Avatar asked Aug 25 '12 22:08

Andrey


1 Answers

It's not a fair test.

  1. The call to CultureInfo.CreateSpecificCulture("en-US") is the slow part. Move it outside the loop, store the result and reuse it.

  2. Your regular expression only handles one specific format, but DateTime.Parse can 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 use DateTime.ParseExact instead of DateTime.Parse.

The fixed code is as follows:

CultureInfo ci = CultureInfo.CreateSpecificCulture("en-US");
for (int i = 0; i < 100000; i++)
{
    DateTime.ParseExact("08/01/2012 23:10:12", "MM/dd/yyyy HH:mm:ss", ci);
}

With these two changes, I get that the DateTime.ParseExact and 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.

like image 78
Mark Byers Avatar answered Oct 03 '22 07:10

Mark Byers