Skip to content

Commit

Permalink
Remove substring allocations from time span extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
Hawxy committed Dec 26, 2024
1 parent 0166e46 commit 35bf606
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
1 change: 1 addition & 0 deletions src/CoreTests/Core/TimeSpanExtensionsTester.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public void to_time_from_string()
"0700".ToTime().ShouldBe(new TimeSpan(7, 0, 0));
"1700".ToTime().ShouldBe(new TimeSpan(17, 0, 0));
"1850".ToTime().ShouldBe(new TimeSpan(18, 50, 0));
"19:05".ToTime().ShouldBe(new TimeSpan(19, 05, 00));
}

[Fact]
Expand Down
13 changes: 7 additions & 6 deletions src/JasperFx/Core/TimeSpanExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static TimeSpan ToTime(this string timeString)

public static TimeSpan GetTimeSpan(string timeString)
{
var match = TimespanRegex().Match(timeString.Trim());
var match = TimespanRegex().Match(timeString);
if (!match.Success)
{
return TimeSpan.Parse(timeString);
Expand Down Expand Up @@ -62,20 +62,21 @@ public static TimeSpan GetTimeSpan(string timeString)
case "days":
return TimeSpan.FromDays(number);
}

var timeSpan = timeString.AsSpan();

if (timeString.Length == 4 && !timeString.Contains(':'))
{
int hours = int.Parse(timeString.Substring(0, 2));
int minutes = int.Parse(timeString.Substring(2, 2));
int hours = int.Parse(timeSpan.Slice(0, 2));
int minutes = int.Parse(timeSpan.Slice(2, 2));

return new TimeSpan(hours, minutes, 0);
}

if (timeString.Length == 5 && timeString.Contains(':'))
{
var parts = timeString.Split(':');
int hours = int.Parse(parts.ElementAt(0));
int minutes = int.Parse(parts.ElementAt(1));
int hours = int.Parse(timeSpan.Slice(0, 2));
int minutes = int.Parse(timeSpan.Slice(3));

return new TimeSpan(hours, minutes, 0);
}
Expand Down

0 comments on commit 35bf606

Please sign in to comment.