Repository navigation
Add missing fast path for DateTime format "G" - #129374
Conversation
Mirrors the existing single-char fast paths for 'o', 'r', 's', 'u' and the null/empty-format invariant fast path that ToString(InvariantCulture) already uses, routing through TryFormatInvariantG instead of FormatCustomized. Output is byte-identical to the existing pattern-based path ("MM/dd/yyyy HH:mm:ss", 19 chars). ~5.5x faster (41.58 ns -> 7.54 ns median).
Co-authored-by: Copilot <[email protected]>
|
Tagging subscribers to this area: @dotnet/area-system-datetime |
There was a problem hiding this comment.
Pull request overview
Adds an invariant-culture fast path for the standard "G" format when formatting a DateTime (i.e., offset.Ticks == NullOffset) by directly using the existing TryFormatInvariantG implementation. This aligns "G" with the existing single-character fast paths (e.g., "o", "r", "s", "u") and the already-existing null/empty-format invariant fast path.
Changes:
- Add a
"G"switch case inDateTimeFormat.Formatthat fast-pathsDateTime.ToString("G", InvariantCulture)toTryFormatInvariantG. - Add the corresponding
"G"fast path inDateTimeFormat.TryFormat<TChar>for invariant culture +DateTime(NullOffset) scenarios.
Show a summary per file
| File | Description |
|---|---|
| src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormat.cs | Adds an invariant "G" fast path in both Format and TryFormat<TChar> using TryFormatInvariantG when offset is NullOffset. |
Copilot's findings
- Files reviewed: 1/1 changed files
- Comments generated: 0
Replace string.FastAllocateString + GetRawStringData with string.Create<TState> in all single-character fast paths in DateTimeFormat.Format (null-format Invariant and IsTimeOnlySpecialCase, DateTimeOffset null+Invariant, 'r'/'R', 's', 'u', and the new 'G'). The previous pattern exposes raw string mutation; string.Create is the idiomatic safe equivalent recommended by the .NET memory-safety design (dotnet/designs#2025/memory-safety) for new code. Also drop the unsafe modifier on Format() since its body no longer uses any unsafe constructs.
|
Asked copilot to measure perf vs main -- Note This comment was drafted with AI assistance (GitHub Copilot CLI) and reviewed by me before posting. Updated measurements — safe
|
| Format | Path | Baseline (ns) | Modified (ns) | Ratio | Notes |
|---|---|---|---|---|---|
"G" + Invariant |
new G fast path | 43.81 | 8.86 | 0.21 | ~5× speedup ✅ |
null + Invariant |
Invariant fast path | 8.10 | 8.51 | 1.06 | ~5% reg from delegate dispatch |
"r" |
TryFormatR fast path | 9.23 | 9.55 | 1.05 | ~5% reg |
"r" + Invariant |
TryFormatR fast path | 9.23 | 9.50 | 1.04 | ~4% reg |
"s" |
TryFormatS fast path | 7.36 | 7.91 | 1.08 | ~8% reg |
"s" + Invariant |
TryFormatS fast path | 7.37 | 7.72 | 1.06 | ~5% reg |
"yyyy-MM-dd HH:mm:ss" + Inv |
not on fast path | 40.07 | 40.46 | 1.04 | within noise (control) |
"o" + Invariant |
not on fast path | 13.13 | 12.85 | 0.99 | flat (control) |
"M/d/yyyy" + Invariant |
not on fast path | 23.06 | 23.11 | 1.00 | flat (control) |
"HH:mm:ss" + Invariant |
not on fast path | 20.69 | 19.66 | 0.98 | flat (control) |
"yyyy-MM-dd" + Invariant |
not on fast path | 22.92 | 22.70 | 0.99 | flat (control) |
"MMMM d, yyyy" + Invariant |
not on fast path | 25.45 | 25.20 | 0.99 | flat (control) |
Controls (formats that don't take a Format() fast path) are flat ± noise, which validates the measurement: only paths I changed move.
About the ~5% regression on the existing fast paths
The 0.3–0.6 ns regression on the pre-existing fast paths is purely the cost of going through SpanAction<char, TState> instead of writing directly into the FastAllocateString result.
string.Create<TState> internally does the same thing we used to do inline:
public static string Create<TState>(int length, TState state, SpanAction<char, TState> action)
{
ArgumentNullException.ThrowIfNull(action);
if (length <= 0) { ... }
string result = FastAllocateString(length);
action(new Span<char>(ref result.GetRawStringData(), length), state);
return result;
}So the entire overhead is: (a) the method call into the generic instantiation, (b) the null + length checks, and (c) the indirect delegate.Invoke to the static-cached lambda. JIT disasm of DateTimeFormat:Format confirms this:
Baseline (unsafe pattern):
6× call System.String:FastAllocateString
2× call System.DateTimeFormat:TryFormatInvariantG[char]
2× call System.DateTimeFormat:TryFormatS[char]
... (TryFormatR, etc.)
Modified (safe pattern):
4× call System.String:Create[DateTime](int, DateTime, SpanAction<char, DateTime>)
3× call System.String:Create[ValueTuple<DateTime,TimeSpan>](...)
|
Asked Copilot to identify necessary work to avoid regression as much as possible -- ==== TL;DRRefactoring 4 existing fast paths in If the JIT could either (a) inline The ~0.3–0.6 ns regression is consistent with one extra non-inlined call + one JIT disasm contrast
Baseline
|
|
I'll have it do some simple experiments tor try recovering the regression without codegen work. |
I do not think that's a good use of time.
|
|
I think your original commit was just fine. |
Restores DateTimeFormat.cs to its state at 80e859d ("Add fast path for DateTime.ToString(""G"", InvariantCulture)"). Measurements showed the safe string.Create(N, state, static lambda) refactor regressed the existing r/s and null-format fast paths by ~10-20% on x64. The original direct FastAllocateString + GetRawStringData pattern is restored to avoid that regression while preserving the new G fast path. Co-authored-by: Copilot <[email protected]>
|
OK, for what it's worth, it recovered the regression with bloaty/complicated code, abandoned that:
Returned this PR to original approach. Ready for signoff. |
|
@EgorBo two pipelines have sat for 6 hours now (waiting for arm64)? |
|
/ba-g timeouts |
Adds a fast path for
DateTime.ToString("G", CultureInfo.InvariantCulture)similar to existing single-char fast path that'o','r','s', and'u'already have inDateTimeFormat.Format/TryFormat<TChar>, and identical to the one the null/empty-format case (dt.ToString(CultureInfo.InvariantCulture)) already takes viaTryFormatInvariantG.The fast path is gated by
offset.Ticks == NullOffset && ReferenceEquals(dtfi, DateTimeFormatInfo.InvariantInfo), soDateTimeOffset.ToString("G", InvariantCulture)and any custom/clonedDateTimeFormatInfofall through to the existing pattern-based path unchanged.Perf Results
5.5x faster
ResultsComparer, threshold 1%, noise 1 ns, 5 launches × 15 iterations × 16384 invocations, P-core pinned on i9-14900K:The remaining 19
Perf_DateTime.ToString*cases (other formats, current-culture,DateTimeOffset) are unchanged. Allocation unchanged everywhere.ToStringInvariant(format)is a new benchmark inPerf_DateTime.csthat callsdate.ToString(format, CultureInfo.InvariantCulture).Tests
Output is byte-identical to the slow path for
DateTime+ invariant culture ("MM/dd/yyyy HH:mm:ss", 19 chars). ExistingDateTime/DateTimeOffsetformatting tests pass. In addition, an ad-hoc correctness harness compared baseline vs. modified outputs over 10 DateTimes (incl.MinValue,MaxValue, year 1, year 9999, Feb 29 2000, allDateTimeKinds) × 5 cultures × 16 formats × {ToString,TryFormat} plus DateTimeOffset equivalents — 1040 byte-identical outputs. Separately verifiedTryFormatwith too-small destinations (sizes 0..20 char, 0..25 UTF-8), composite formatting$"{dt:G}", cloned DTFI, and DTFI with customizedLongTimePattern— all behave identically to baseline.Note
This PR description was drafted by GitHub Copilot.