Performance of DateTime.Parse()

Published on Wednesday, September 19, 2007
I would like to write a series of posts describing the various performance issues I faced while implementing DotSVN.

In this post I discuss the performance penalty of using DateTime.Parse().

During my testing, I found that DotSVN was running quite slow. I used a trial version of 'JetBrains dotTrace 3.0' to analyze the problem. The following is a screen-shot of the dotTrace session.
DateTime.Parse() Performance issue

As you can see, 26% of the time is spend on the method call 'System.DateTime.Parse()'. This was unacceptable. After some investigation I found that the performance of the DateTime Parse method can be improved if we give some clue on formatting of the date string. This can be achieved using the ParseExact() method.

note: I have updated the code to re-use the CultureInfo class.
AlexKucherenko - Thanks for the comment.



private static readonly CultureInfo en_us_Culture = new CultureInfo("en-US");

// Parse in the format [2007-09-06T10:20:26.689093Z]
private static readonly string dateTimeFormat = "yyyy-MM-ddTHH:mm:ss.FFFFFFFZ";

public static DateTime parseDate(String dateString)
{
	DateTime parsedDate;

	bool parseResult = DateTime.TryParseExact(dateString, dateTimeFormat, 
							en_us_Culture, 
							DateTimeStyles.AdjustToUniversal, out parsedDate);
	if(!parseResult)
	{
		SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_DATE);
		SVNErrorManager.error(err);    
	}
	return parsedDate;
}


The performance gain is quite obvious with the following figure, which shows the dotTrace session after applying the above fix.
DateTime.ParseExact() solution

As you can see, DateTime.Parse() is no longer a hot Spot. This also shows the power of dotTrace, and how it helped to quickly narrow down the issue.
comments powered by Disqus