Skip to content

[repo-assist] perf: replace compiled Regex with [GeneratedRegex] source-generated regex#17

Draft
github-actions[bot] wants to merge 1 commit into
mainfrom
repo-assist/perf-generated-regex-2026-06-f3884b36555c2e78
Draft

[repo-assist] perf: replace compiled Regex with [GeneratedRegex] source-generated regex#17
github-actions[bot] wants to merge 1 commit into
mainfrom
repo-assist/perf-generated-regex-2026-06-f3884b36555c2e78

Conversation

@github-actions

Copy link
Copy Markdown
Contributor

🤖 This pull request was created by Repo Assist, an automated AI assistant.

Summary

Replace the runtime-compiled static readonly Regex field in TryParse with a source-generated partial method using the [GeneratedRegex] attribute.

What changed

DateTimeNano is now declared partial struct, and the DateTimeRegex static field is replaced with:

[GeneratedRegex(
    @"(?<year>\d+)-(?<month>\d+)-...")]
private static partial Regex DateTimeRegex();

TryParse calls DateTimeRegex() instead of accessing the field.

Why

Concern Old (RegexOptions.Compiled) New ([GeneratedRegex])
Compilation time First static-field access (startup overhead) Build time — zero runtime cost
AOT / NativeAOT ❌ Not compatible ✅ Fully compatible
Runtime performance Good Equal or better on .NET 8+
Regex validation Runtime Compile time

[GeneratedRegex] was introduced in .NET 7 and is the recommended approach for .NET 8/9/10+ projects. The library already targets net8.0;net9.0;net10.0, so there is no framework constraint.

Trade-offs

  • The struct must be partial, but this is a non-breaking change — no public API surface changes.

Test Status

✅ All 40 tests pass on net8.0. Build succeeded for net8.0, net9.0, and net10.0 with 0 warnings.

Generated by 🌈 Repo Assist, see workflow run. Learn more.

…egex

Use the [GeneratedRegex] attribute (available since .NET 7) to replace the
runtime-compiled static Regex field in DateTimeNano.TryParse with a
source-generated partial method.

Benefits:
- Regex is compiled at build time, not at first access, eliminating startup
  overhead when the static field is first touched.
- Generated code is typically faster than RegexOptions.Compiled at runtime
  for .NET 8+.
- Enables full AOT/NativeAOT compatibility (compiled regexes are not
  AOT-friendly; source-generated ones are).
- Compile-time validation of the regex pattern.

The struct is now declared partial (no public API change). All 40 existing
tests pass unchanged on net8.0.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants