Skip to content

Commit

Permalink
Replace try-catch parser with TryParse
Browse files Browse the repository at this point in the history
This fixes some performance issues when trying to parse dates
  • Loading branch information
dezhidki committed Jan 5, 2022
1 parent 91e8fff commit ecac69d
Showing 1 changed file with 13 additions and 19 deletions.
32 changes: 13 additions & 19 deletions Tommy/Tommy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1151,10 +1151,10 @@ var v when TomlSyntax.IsFloat(v) => double.Parse(value.RemoveAll(TomlSyntax.INT_

// Normalize by removing space separator
value = value.Replace(TomlSyntax.RFC3339EmptySeparator, TomlSyntax.ISO861Separator);
if (StringUtils.TryParseDateTime(value,
if (StringUtils.TryParseDateTime<DateTime>(value,
TomlSyntax.RFC3339LocalDateTimeFormats,
DateTimeStyles.AssumeLocal,
DateTime.ParseExact,
DateTime.TryParseExact,
out var dateTimeResult,
out var precision))
return new TomlDateTimeLocal
Expand All @@ -1177,7 +1177,7 @@ var v when TomlSyntax.IsFloat(v) => double.Parse(value.RemoveAll(TomlSyntax.INT_
if (StringUtils.TryParseDateTime(value,
TomlSyntax.RFC3339LocalTimeFormats,
DateTimeStyles.AssumeLocal,
DateTime.ParseExact,
DateTime.TryParseExact,
out dateTimeResult,
out precision))
return new TomlDateTimeLocal
Expand All @@ -1187,12 +1187,12 @@ var v when TomlSyntax.IsFloat(v) => double.Parse(value.RemoveAll(TomlSyntax.INT_
SecondsPrecision = precision
};

if (StringUtils.TryParseDateTime(value,
TomlSyntax.RFC3339Formats,
DateTimeStyles.None,
DateTimeOffset.ParseExact,
out var dateTimeOffsetResult,
out precision))
if (StringUtils.TryParseDateTime<DateTimeOffset>(value,
TomlSyntax.RFC3339Formats,
DateTimeStyles.None,
DateTimeOffset.TryParseExact,
out var dateTimeOffsetResult,
out precision))
return new TomlDateTimeOffset
{
Value = dateTimeOffsetResult,
Expand Down Expand Up @@ -1996,10 +1996,12 @@ public static string Join(this string self, IEnumerable<string> subItems)
return sb.ToString();
}

public delegate bool TryDateParseDelegate<T>(string s, string format, IFormatProvider ci, DateTimeStyles dts, out T dt);

public static bool TryParseDateTime<T>(string s,
string[] formats,
DateTimeStyles styles,
Func<string, string, CultureInfo, DateTimeStyles, T> parser,
TryDateParseDelegate<T> parser,
out T dateTime,
out int parsedFormat)
{
Expand All @@ -2008,15 +2010,7 @@ public static bool TryParseDateTime<T>(string s,
for (var i = 0; i < formats.Length; i++)
{
var format = formats[i];
try
{
dateTime = parser(s, format, CultureInfo.InvariantCulture, styles);
}
catch (Exception)
{
continue;
}

if (!parser(s, format, CultureInfo.InvariantCulture, styles, out dateTime)) continue;
parsedFormat = i;
return true;
}
Expand Down

0 comments on commit ecac69d

Please sign in to comment.