Alex Rivera | Logout

Is DateTime.ParseExact() faster than DateTime.Parse()

Asked 2010-03-24T09:19:18.190
13

I would like to know if ParseExact is faster than Parse.

I think that it should be ParseExact since you already gave the format but I also think all the checking for the Culture info would slow it down. Does microsoft say in any document on performance difference between the two. The format to be used is a generic 'yyyy/MM/dd' format .

For example:

DateTime.Parse(DateText);
DateTime.ParseExact(DateText, "yyyy/MM/dd", CultureInfo.InvariantCulture);
Edit
Report

1 Answer

5

If you specify only one format forTryParseExact that is all it will try. Parse tries all formats either until a best match is found or the first match is found. (I am not sure which.) I did this a few weeks ago, with a customized CultureInfo. I did not test performance, but I did run unit tests on my parse methods (without the customized CultureInfo, see below) against 61,880 dates stored in a database. I did not notice any performance issues.

Regardless if you specify a CultureInfo or not, the internal parsing routines will use CultureInvariant if none is passed. Therefore, CultureInfo does not slow down the process. (There are some performance hits for Hebrew and other "exotic" dates due to extra parsing they require.) From my review of the source code for DateTime, the number of string formats determines how fast these routines can parse a date string. The more format, the slower. If you are only specifying one, then the parsing is as fast as it can be with the ...Exact methods.


Imports System.Globalization

Public Class ExifDateTime

    Private Shared _formats() As String = New String() { _
        "yyyy:MM:dd", _
        "yyyy:MM:dd HH:mm:ss", _
        "yyyy:MM:dd HH:mm:ss.f", _
        "yyyy:MM:dd HH:mm:ss.ff", _
        "yyyy:MM:dd HH:mm:ss.fff", _
        "yyyy:MM:dd HH:mm:ss.fffK", _
        "yyyy:MM:dd HH:mm:ss.ffffffK", _
        "yyyy:MM:dd HH:mm:ssK", _
        ""}


    Public Shared Function Parse(ByVal s As String) As Date
        Dim oResult As Date
        If TryParse(s, DateTimeStyles.None, oResult) = False Then
            Throw New FormatException
        End If
        Return oResult
    End Function

    Public Shared Function Parse(ByVal s As String, ByVal style As System.Globalization.DateTimeStyles) As Date
        Dim oResult As Date
        If TryParse(s, style, oResult) = False Then
            Throw New FormatException
        End If
        Return oResult
    En
answered 2010-03-24T10:24:05.107

Your Answer