You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[System.Text.Json] Replace JsonHelpers.IntegerRegex with a lexical scan #136184
EnumConverter uses JsonHelpers.IntegerRegex.IsMatch(source) to classify whether a string is an integer. This is a purely lexical check "is this a base-10 integer literal?" which could be done with a small allocation-free scan instead of the regex engine.
Proposal
Add an internal helper and use it instead of the existing regex:
public static bool IsInteger(ReadOnlySpan<char> s)
{
s = s.Trim();
if (s.IsEmpty)
return false;
if (s[0] is '+' or '-')
s = s[1..];
if (s.IsEmpty)
return false;
foreach (char c in s)
{
if ((uint)(c - '0') > 9)
return false;
}
return true;
}
Benchmark
To compare existing regex with the proposed method I ran a simple BenchmarkDotNet project with results attached below:
using System.Text.RegularExpressions;
namespace App;
public partial class IntegerMatcher
{
private const string IntegerRegexPattern = @"^\s*(?:\+|\-)?[0-9]+\s*$";
private const int IntegerRegexTimeoutMs = 200;
[GeneratedRegex(IntegerRegexPattern, RegexOptions.None, matchTimeoutMilliseconds: IntegerRegexTimeoutMs)]
public static partial Regex IntegerRegex { get; }
public static bool IsInteger(ReadOnlySpan<char> s)
{
s = s.Trim();
if (s.IsEmpty)
return false;
if (s[0] is '+' or '-')
s = s[1..];
if (s.IsEmpty)
return false;
foreach (char c in s)
{
if ((uint)(c - '0') > 9)
return false;
}
return true;
}
}
Benchmark:
using App;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<IntegerStringBenchmarks>();
[MemoryDiagnoser]
public class IntegerStringBenchmarks
{
[Params("IntShort", "Negative", "Name", "AllDigits", "Overflow", "Padded")]
public string Case = "IntShort";
private string _input = "";
[GlobalSetup]
public void Setup() => _input = Case switch
{
"IntShort" => "42",
"Negative" => "-7",
"Name" => "Monday",
"AllDigits" => "1234567890",
"Overflow" => "9999921331999991199999999990012399999",
"Padded" => " 123 ",
_ => throw new ArgumentOutOfRangeException(nameof(Case)),
};
[Benchmark(Baseline = true)]
public bool IntegerRegex() => IntegerMatcher.IntegerRegex.IsMatch(_input);
[Benchmark]
public bool IsInteger() => IntegerMatcher.IsInteger(_input);
}
I pulled the generated TryMatchAtCurrentPosition body out into a plain static method (no RegexRunner) and benched it against the regex (IntegerRegex - existing IntegerRegex.IsMatch, IsInteger - custom implementation presented above, IsInteger2 - extracted matching logic from TryMatchAtCurrentPosition) :
The gap between the IntegerRegex and the IsInteger2 (extracted body) is flat no matter the input, so it seems to be a fixed per-call overhead, not the matching.
An improvement idea would be a flattened emit for simple fully-anchored, backtracking-free patterns that skips the runner wrapper. That’d fix it everywhere rather than just this one call site - but I’m happy to follow whichever direction you prefer, and glad to take a crack at it if it’d help. Thanks in advance for taking a look!
One way or another, your suggestion is backed by an isolated benchmark, ideally, you should apply your change to STJ and run some benchmark for baseline vs PR to prove it moves the needle.
so it seems to be a fixed per-call overhead, not the matching.
As you suggested I applied changes to STJ and benchmarked (I ran baseline vs proposed changes using --corerun) - no performance gain in this area.
While profiling regex stuff, though, I found something interesting. The _nameCacheForReading.Count check before TryAdd in EnumConverter is ConcurrentDictionary.Count, which acquires all of the dictionary’s internal locks on every call. The converter’s constructor pre-fills _nameCacheForReading with every enum name. So once an enum has >= 64 members the following takes place:
numeric string values never match a name so they miss the cache, and
because Count ≥ 64, they can never be added so every such read hits ConcurrentDictionary.Count (the all-locks path), on every deserialize
The 60/61 jump is the threshold: at 60 the four parsed values still fit under the limit and get cached (so the change is a no-op — no regression), and at 61 the cache is saturated and the lock-storm begins, scaling with enum size. The same .Count pattern seems to be on the serialization/write path too.
On thread-safety: the counter isn’t strictly exact under concurrency, but the existing Count < limit + TryAdd is already a non-atomic check-then-act, and the cache is append-only - so this preserves current behavior and just removes the lock acquisition.
Activity
dotnet-policy-service commentedon Oct 20, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
tglowka commentedon Oct 20, 2026
Wrong label assigned. Could someone change it to area-System.Text.Json?
Thanks!
EgorBo commentedon Oct 20, 2026
Isn't it basically what Regex does?
Please attach the full snippet, I suspect you didn't use the SG-backed Regex.
dotnet-policy-service commentedon Oct 20, 2026
Tagging subscribers to this area: @dotnet/area-system-text-json
See info in area-owners.md if you want to be subscribed.
tglowka commentedon Oct 20, 2026
App:
Benchmark:
EgorBo commentedon Oct 20, 2026
anyway, this feels like handling/improving it on Regex level is something that will benefit everyrone I guess
tglowka commentedon Oct 21, 2026
Could you elaborate?
eiriktsarpalis commentedon Oct 21, 2026
Egor is suggesting that making relevant improvements in the regex generator itself is preferable.
tglowka commentedon Oct 21, 2026
I pulled the generated
TryMatchAtCurrentPositionbody out into a plain static method (no RegexRunner) and benched it against the regex (IntegerRegex- existingIntegerRegex.IsMatch,IsInteger- custom implementation presented above,IsInteger2- extracted matching logic fromTryMatchAtCurrentPosition) :The gap between the
IntegerRegexand theIsInteger2(extracted body) is flat no matter the input, so it seems to be a fixed per-call overhead, not the matching.An improvement idea would be a flattened emit for simple fully-anchored, backtracking-free patterns that skips the runner wrapper. That’d fix it everywhere rather than just this one call site - but I’m happy to follow whichever direction you prefer, and glad to take a crack at it if it’d help. Thanks in advance for taking a look!
EgorBo commentedon Oct 21, 2026
One way or another, your suggestion is backed by an isolated benchmark, ideally, you should apply your change to STJ and run some benchmark for baseline vs PR to prove it moves the needle.
Perhaps it should be inlined then? 🤷
tglowka commentedon Oct 26, 2026
As you suggested I applied changes to STJ and benchmarked (I ran baseline vs proposed changes using --corerun) - no performance gain in this area.
While profiling regex stuff, though, I found something interesting. The
_nameCacheForReading.Countcheck beforeTryAddinEnumConverterisConcurrentDictionary.Count, which acquires all of the dictionary’s internal locks on every call. The converter’s constructor pre-fills_nameCacheForReadingwith every enum name. So once an enum has >= 64 members the following takes place:I ran the following benchmark:
and obtained the results:
The 60/61 jump is the threshold: at 60 the four parsed values still fit under the limit and get cached (so the change is a no-op — no regression), and at 61 the cache is saturated and the lock-storm begins, scaling with enum size. The same .Count pattern seems to be on the serialization/write path too.
On thread-safety: the counter isn’t strictly exact under concurrency, but the existing
Count < limit + TryAddis already a non-atomic check-then-act, and the cache is append-only - so this preserves current behavior and just removes the lock acquisition.EgorBo commentedon Oct 27, 2026
@tglowka want to file a PR with this improvement? I think it makes sense. (or I can try on your behalf if you want).
tglowka commentedon Oct 27, 2026
@EgorBo Sure thing, I will prepare a PR! The PR should point to this issue (or the other way around), right?
EgorBo commentedon Oct 27, 2026
I filed #136516, feel free to submit a PR