Skip to content

Commit

Permalink
optimize DateTimeOffset.UtcNow by removing redundant verification (#4…
Browse files Browse the repository at this point in the history
…5281)

* optimize DateTimeOffset.UtcNow by removing redundant verification, cuts 10% of time on Windows

* Update src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs

Co-authored-by: Stephen Toub <[email protected]>
  • Loading branch information
adamsitnik and stephentoub authored Nov 30, 2020
1 parent 839ad29 commit 00417de
Showing 1 changed file with 19 additions and 6 deletions.
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

0 comments on commit 00417de

Please sign in to comment.