Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optimize DateTimeOffset.UtcNow by removing redundant verification #45281

Merged
merged 3 commits into from
Nov 30, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,15 @@ namespace System

// Constructors

private DateTimeOffset(short validOffsetMinutes, DateTime validDateTime)
{
_dateTime = validDateTime;
_offsetMinutes = validOffsetMinutes;
}

// Constructs a DateTimeOffset from a tick count and offset
public DateTimeOffset(long ticks, TimeSpan offset)
public DateTimeOffset(long ticks, TimeSpan offset) : this(ValidateOffset(offset), ValidateDate(new DateTime(ticks), offset))
{
_offsetMinutes = ValidateOffset(offset);
// Let the DateTime constructor do the range checks
DateTime dateTime = new DateTime(ticks);
_dateTime = ValidateDate(dateTime, offset);
}

// Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds,
Expand Down Expand Up @@ -174,7 +176,18 @@ public DateTimeOffset(int year, int month, int day, int hour, int minute, int se
// resolution of the returned value depends on the system timer.
public static DateTimeOffset Now => ToLocalTime(DateTime.UtcNow, true);

public static DateTimeOffset UtcNow => new DateTimeOffset(DateTime.UtcNow);
public static DateTimeOffset UtcNow
{
get
{
DateTime utcNow = DateTime.UtcNow;
var result = new DateTimeOffset(0, utcNow);

Debug.Assert(new DateTimeOffset(utcNow) == result); // ensure lack of verification does not break anything

return result;
}
}

public DateTime DateTime => ClockDateTime;

Expand Down