Skip to content

Add missing fast path for DateTime format "G" - #129374

Merged
danmoseley merged 5 commits into
dotnet:mainfrom
danmoseley:runtime-dtfmt-modified
Jun 17, 2026
Merged

danmoseley merged 5 commits into
dotnet:mainfrom
danmoseley:runtime-dtfmt-modified

Conversation

@danmoseley

@danmoseley danmoseley commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

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 in DateTimeFormat.Format / TryFormat<TChar>, and identical to the one the null/empty-format case (dt.ToString(CultureInfo.InvariantCulture)) already takes via TryFormatInvariantG.

The fast path is gated by offset.Ticks == NullOffset && ReferenceEquals(dtfi, DateTimeFormatInfo.InvariantInfo), so DateTimeOffset.ToString("G", InvariantCulture) and any custom/cloned DateTimeFormatInfo fall 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:

summary: better: 1, geomean: 5.511, total diff: 1
No Slower results for the provided threshold = 1% and noise filter = 1 ns.
Faster base/diff Base Median (ns) Diff Median (ns)
System.Tests.Perf_DateTime.ToStringInvariant(format: "G") 5.51 41.58 7.54

The remaining 19 Perf_DateTime.ToString* cases (other formats, current-culture, DateTimeOffset) are unchanged. Allocation unchanged everywhere.

ToStringInvariant(format) is a new benchmark in Perf_DateTime.cs that calls date.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). Existing DateTime / DateTimeOffset formatting 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, all DateTimeKinds) × 5 cultures × 16 formats × {ToString, TryFormat} plus DateTimeOffset equivalents — 1040 byte-identical outputs. Separately verified TryFormat with too-small destinations (sizes 0..20 char, 0..25 UTF-8), composite formatting $"{dt:G}", cloned DTFI, and DTFI with customized LongTimePattern — all behave identically to baseline.

Note

This PR description was drafted by GitHub Copilot.

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]>
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-datetime
See info in area-owners.md if you want to be subscribed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 in DateTimeFormat.Format that fast-paths DateTime.ToString("G", InvariantCulture) to TryFormatInvariantG.
  • Add the corresponding "G" fast path in DateTimeFormat.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.
@danmoseley

Copy link
Copy Markdown
Contributor Author

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 string.Create refactor

Per review feedback, I refactored all 7 of the Format() fast paths from the existing unsafe FastAllocateString + GetRawStringData() pattern to safe string.Create<TState> with static lambdas (commit 6290b7d). This both adds the new "G" + invariant fast path and modernizes the existing 4 paths (IsTimeOnlySpecialCase, Invariant + null offset, Invariant + DTO, "r"/"R", "s", "u") off the unsafe pattern.

Benchmark results

BenchmarkDotNet, 3 launches × 15 iterations × 5 warmup × 16384 invocations, P-core 0 affinity (Intel i9-14900K), --memory, both runtimes built from the same upstream main commit; only DateTimeFormat.cs differs. Tests filtered to *Perf_DateTime.ToString* in dotnet/performance.

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>](...)

@danmoseley

danmoseley commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Asked Copilot to identify necessary work to avoid regression as much as possible --

====

TL;DR

Refactoring 4 existing fast paths in DateTimeFormat.Format from the unsafe
FastAllocateString + GetRawStringData() pattern to safe
string.Create<TState>(length, state, static lambda) introduces a 4–8% (≈ 0.3–0.6 ns)
regression on hot paths (DateTime.ToString("r"/"s"/null)). The cost is purely an
inlining/devirtualization failure in the JIT: string.Create<TState> is never
inlined into the caller, and the SpanAction<char, TState> field load is never
devirtualized even though the C# compiler caches the static lambda into a readonly
static field whose target+method are knowable at JIT time.

If the JIT could either (a) inline string.Create<TState> into the call site so it
sees the static-cached delegate, or (b) devirtualize a Delegate.Invoke whose
target is a statically-known cached singleton, the safe pattern would compile to
equivalent code to the unsafe pattern. This would remove the cost barrier for
modernizing other BCL hot paths off the unsafe FastAllocateString +
GetRawStringData pattern.

The ~0.3–0.6 ns regression is consistent with one extra non-inlined call + one
extra indirect call
at modern x86-64 prediction throughput on a 5+ GHz core.

JIT disasm contrast

DOTNET_JitDisasm=Format DOTNET_TieredCompilation=0 DOTNET_ReadyToRun=0 on a tiny
driver calling DateTime.ToString("r") + DateTime.ToString("G", InvariantCulture)
in a hot loop, on both runtimes:

Baseline DateTimeFormat:Format — 15.7 KB disasm

6×  call  System.String:FastAllocateString(...)
2×  call  System.DateTimeFormat:TryFormatInvariantG[char](...)
2×  call  System.DateTimeFormat:TryFormatS[char](...)
1×  call  System.DateTimeFormat:TryFormatR[char](...)   (and so on for other paths)

The unsafe pattern compiles to: allocate the string directly, then call the
TryFormatX helper to write into the GetRawStringData-backed span. Two calls
per fast path: one FastAllocateString, one TryFormatX.

Modified DateTimeFormat:Format — 22.9 KB disasm

4×  call  System.String:Create[System.DateTime](
            int,
            System.DateTime,
            System.Buffers.SpanAction`2[char, System.DateTime])
3×  call  System.String:Create[System.ValueTuple`2[DateTime, TimeSpan]](
            int,
            System.ValueTuple`2[DateTime, TimeSpan],
            System.Buffers.SpanAction`2[char, ValueTuple`2[DateTime, TimeSpan]])

Every fast path becomes a single call to the appropriate generic instantiation of
string.Create<TState>. Inside that instantiation (not inlined), the body does:

  1. if (action is null) throw ... — null check
  2. if (length <= 0) branch
  3. string result = FastAllocateString(length) — same as baseline
  4. action(new Span<char>(ref result.GetRawStringData(), length), state) —
    indirect Delegate.Invoke to the static-cached lambda
  5. return result

So the per-fast-path delta is:

  • +1 non-inlined method call (into string.Create<TState>)
  • +1 null check, +1 length check (cheap, but real)
  • +1 indirect call through SpanAction<char, TState>.Invoke (this is the dominant
    cost — branch predictor must learn the indirect target, and the call cannot fold
    into the surrounding code)
  • The compensating save is that the body of e.g. TryFormatR is now reachable only
    through the delegate, but on the baseline path it was already a call (not
    inlined), so there is no offsetting saving in practice.

Why the JIT can't fix it today

  1. string.Create<TState> is not inlined. The body contains a null check,
    length check, allocation helper call, and indirect delegate invocation. Its IL
    size and call complexity exceed the inliner's budget for generic instantiations.
    Even if it were inlined, …
  2. The SpanAction<char, TState> reference is opaque to the JIT. It arrives as
    a parameter; the inliner doesn't propagate the fact that the caller passed
    <>c.<>9__N_M (the cached static singleton holding the static lambda). So the
    Delegate.Invoke call site inside string.Create (or, hypothetically, inlined
    into the caller) is treated as a fully indirect call.
  3. Even at the call site itself, the JIT does not devirtualize
    Delegate.Invoke calls where the target is a static readonly field whose value
    is a known-non-null cached delegate. Tracked at a high level by
    Inline for lambda #13679 (Inline for lambda) and optimization of indirect calls #44610 (optimization of indirect
    calls).

What would unblock the modernization

Any one of these would close the gap:

  1. Inline string.Create<TState> into the caller when length is a literal /
    small constant and state / action are propagated through. Then the call site
    sees <>c.<>9__N_M directly and the existing delegate-devirtualization
    improvements (GDV) would have a chance.
  2. Devirtualize Delegate.Invoke to a statically-known cached singleton. When
    action is loaded from a private static readonly field and the field's value
    is provably the delegate constructed in the cctor / lazy-cache pattern emitted
    by the C# compiler, the JIT could promote the call to a direct call to the
    compiler-generated <>c.<…>b__N_M static method (which is itself trivially
    inlinable).
  3. [MethodImpl(MethodImplOptions.AggressiveInlining)] on string.Create<TState>
    — most modest fix. May get the inliner to copy the body, after which point the
    already-static delegate field load is in the same method as its use and existing
    constant-prop / devirt may kick in.

Option (3) is the cheapest experiment and could be tried first; if it works, it's a
one-line change to String.cs.

Self-contained repro

Measured string.Create(N, state, static lambda) against a hand-rolled equivalent that
allocates a string and writes into it via MemoryMarshal.CreateSpan +
Unsafe.AsRef(in s.GetPinnableReference()). Run via baseline corerun:

Program.cs (click to expand)
using System;
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

class Program
{
    const int Length = 19;
    static int s_sink;

    static void Main()
    {
        for (int i = 0; i < 200_000; i++)
        {
            s_sink += ViaCreate().Length;
            s_sink += ViaDirect().Length;
        }
        Console.WriteLine($"warm done, sink={s_sink}");

        const int N = 50_000_000;
        double tA = double.MaxValue, tB = double.MaxValue;
        long sumA = 0, sumB = 0;

        for (int run = 0; run < 3; run++)
        {
            var sw = Stopwatch.StartNew();
            long s = 0; for (int i = 0; i < N; i++) s += ViaCreate().Length;
            sw.Stop(); sumA = s;
            tA = Math.Min(tA, sw.Elapsed.TotalNanoseconds / N);

            sw.Restart();
            s = 0; for (int i = 0; i < N; i++) s += ViaDirect().Length;
            sw.Stop(); sumB = s;
            tB = Math.Min(tB, sw.Elapsed.TotalNanoseconds / N);
        }
        Console.WriteLine($"ViaCreate  (string.Create<TState> + static lambda): {tA,7:F2} ns/op  sum={sumA}");
        Console.WriteLine($"ViaDirect  (direct call, no delegate)            : {tB,7:F2} ns/op  sum={sumB}");
        Console.WriteLine($"Delta (delegate dispatch overhead)               : {tA-tB,7:F2} ns/op  ({100*(tA-tB)/tB:F1}%)");
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    static string ViaCreate() => string.Create(Length, 0, static (dest, _) => Fill(dest));

    [MethodImpl(MethodImplOptions.NoInlining)]
    static string ViaDirect()
    {
        string s = FastAllocLookalike(Length);
        var span = MemoryMarshal.CreateSpan(ref Unsafe.AsRef(in s.GetPinnableReference()), Length);
        Fill(span);
        return s;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    static string FastAllocLookalike(int len) => new string('\0', len);

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static void Fill(Span<char> dest)
    {
        for (int i = 0; i < dest.Length; i++) dest[i] = (char)('0' + (i % 10));
    }
}
warm done, sink=7600000
ViaCreate  (string.Create<TState> + static lambda):   13.34 ns/op
ViaDirect  (direct call, no delegate)            :   14.68 ns/op

⚠️ The repro understates the delegate cost because ViaDirect substitutes
new string('\0', N) for FastAllocateString — that ctor writes N zero chars
which FastAllocateString skips, adding ~1–2 ns to ViaDirect. The repro
nonetheless demonstrates the call-shape difference; the authoritative numbers
are the BDN results in the table above.

Existing tracking issues

Recommended next steps

  1. File new issue "JIT: inline string.Create<TState> so static-cached
    SpanAction can devirtualize", citing this analysis, the BDN deltas, and the
    disasm contrast. Tag area-CodeGen-coreclr, tenet-performance.
  2. Try AggressiveInlining on string.Create<TState> as a one-line spike
    to see whether inlining alone (without devirt) eliminates the regression. If
    it does, propose it as a small standalone PR.
  3. Hold PR Add missing fast path for DateTime format "G" #129374 on the safe-refactor side until the codegen work lands.
    Alternatively, split the PR: ship just the "G" case using the existing
    unsafe pattern for .NET 10 (small, low-risk win), and defer the safe-refactor
    of all 7 paths until JIT improvements close the gap.

@danmoseley

Copy link
Copy Markdown
Contributor Author

I'll have it do some simple experiments tor try recovering the regression without codegen work.

@jkotas

jkotas commented Jun 14, 2026

Copy link
Copy Markdown
Member

I'll have it do some simple experiments to try recovering the regression without codegen work.

I do not think that's a good use of time.

  • We have some idea what it would take to fix the perf overhead of string.Create vs. internal unsafe CoreLib pattern.
  • Until that happens, it is ok to use the internal unsafe CoreLib pattern in low-level formatting routines for basic types where it is used today.

@jkotas

jkotas commented Jun 14, 2026

Copy link
Copy Markdown
Member

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]>
Copilot AI review requested due to automatic review settings June 14, 2026 22:32
@danmoseley

danmoseley commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor Author

OK, for what it's worth, it recovered the regression with bloaty/complicated code, abandoned that:

Generic struct filler with static abstract interface: replaced the lambda in string.Create(N, state, static (d,s) => …) with a new internal overload string.Create<TFiller, TState>(int, TState) where TFiller : struct, IStringFiller plus an empty readonly struct per fast path. Because TFiller is a value type, the JIT specializes per-instantiation, resolves the static abstract Fill to a direct call, and inlines through — leaving the same FastAllocateString → TryFormatX[char] codegen as the original unsafe version, with no unsafe at the call sites.

Returned this PR to original approach. Ready for signoff.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot's findings

  • Files reviewed: 1/1 changed files
  • Comments generated: 1

Copilot AI review requested due to automatic review settings June 15, 2026 15:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot's findings

  • Files reviewed: 1/1 changed files
  • Comments generated: 0 new

@danmoseley

Copy link
Copy Markdown
Contributor Author

@EgorBo two pipelines have sat for 6 hours now (waiting for arm64)?

@EgorBo

EgorBo commented Jun 17, 2026

Copy link
Copy Markdown
Member

/ba-g timeouts

@danmoseley
danmoseley merged commit 7f8276d into dotnet:main Jun 17, 2026
150 of 154 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview6 milestone Jun 18, 2026
@danmoseley
danmoseley deleted the runtime-dtfmt-modified branch June 18, 2026 20:20
@github-actions github-actions Bot locked and limited conversation to collaborators Jul 19, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants