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
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
End Function
Public Shared Function TryParse(ByVal s As String, ByRef result As Date) As Boolean
Return TryParse(s, DateTimeStyles.None, result)
End Function
Public Shared Function TryParse(ByVal s As String, ByVal style As System.Globalization.DateTimeStyles, ByRef result As Date) As Boolean
Dim fResult As Boolean
Dim oResultant As Date
fResult = Date.TryParseExact(s, _formats, CultureInfo.InvariantCulture, style, oResultant)
If fResult Then
result = oResultant
End If
Return fResult
End Function
End Class