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 DateTime constructors (DateToTicks and IsLeapYear) #46245

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
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
8 changes: 5 additions & 3 deletions src/libraries/System.Private.CoreLib/src/System/DateTime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -635,8 +635,8 @@ private static long DateToTicks(int year, int month, int day)
ThrowHelper.ThrowArgumentOutOfRange_BadYearMonthDay();
}

int y = year - 1;
int n = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
uint y = (uint)(year - 1);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A similar optimization is part of #46245

uint n = y * 365 + y / 4 - y / 100 + y / 400 + (uint)days[month - 1] + (uint)day - 1;
return n * TicksPerDay;
}
Copy link
Member Author

@EgorBo EgorBo Dec 19, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

y is int but always is in the [1..9999] range so can be treated as unsigned (X /u C is faster than X / C) sharplab.io


Expand Down Expand Up @@ -1130,7 +1130,9 @@ public static bool IsLeapYear(int year)
{
ThrowHelper.ThrowArgumentOutOfRange_Year();
}
return (year & 3) == 0 && ((year & 15) == 0 || (year % 25) != 0);
return (year & 3) == 0 && ((year & 15) == 0 ||
// TODO: optimize "(uint)year % 25 != 0" in JIT to produce:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we should fix the JIT instead of sprinkling manually generated magic div and mod everywhere. I had the same comment in #45479 (comment)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah didn't notice that pr 🙂

(year * -1030792151 > 171798691));
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


// Constructs a DateTime from a string. The string must specify a
Expand Down