Skip to content

[System.Text.Json] Replace JsonHelpers.IntegerRegex with a lexical scan #136184

Description

@tglowka

Summary

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:

BenchmarkDotNet v0.15.8, Linux Ubuntu 24.04.5 LTS (Noble Numbat)
Intel Core Ultra 9 275HX 0.80GHz, 1 CPU, 24 logical and 24 physical cores
.NET SDK 10.0.113
[Host] : .NET 10.0.13 (10.0.13, 10.0.1326.50504), X64 RyuJIT x86-64-v3
DefaultJob : .NET 10.0.13 (10.0.13, 10.0.1326.50504), X64 RyuJIT x86-64-v3

Method Case Mean Ratio Allocated
IntegerRegex AllDigits 26.535 ns 1.00 -
IsInteger AllDigits 5.984 ns 0.23 -
IntegerRegex IntShort 26.894 ns 1.00 -
IsInteger IntShort 2.026 ns 0.08 -
IntegerRegex Name 24.597 ns 1.00 -
IsInteger Name 1.709 ns 0.07 -
IntegerRegex Negative 26.554 ns 1.00 -
IsInteger Negative 2.396 ns 0.09 -
IntegerRegex Overflow 26.943 ns 1.00 -
IsInteger Overflow 15.792 ns 0.59 -
IntegerRegex Padded 29.342 ns 1.00 -
IsInteger Padded 10.287 ns 0.35 -

Tested scenarios:
AllDigits" => "1234567890"
IntShort" => "42"
Name" => "Monday"
Negative" => "-7"
Overflow" => "9999921331999991199999999990012399999"
Padded" => " 123 "

Question

Is the measured CPU delta worth the change? Happy to open the PR if an area owner agrees.

Activity

  1. added
    untriaged
    on Oct 20, 2026
  2. added
    area-CodeGen-coreclr
    on Oct 20, 2026
  3. dotnet-policy-service commented on Oct 20, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  4. tglowka commented on Oct 20, 2026

    @tglowka
    Author

    Wrong label assigned. Could someone change it to area-System.Text.Json?
    Thanks!

  5. EgorBo commented on Oct 20, 2026

    @EgorBo
    Member

    Isn't it basically what Regex does?

    Image

    Please attach the full snippet, I suspect you didn't use the SG-backed Regex.

  6. added and removed
    area-CodeGen-coreclr
    on Oct 20, 2026
  7. dotnet-policy-service commented on Oct 20, 2026

    @dotnet-policy-service
    Contributor

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

  8. tglowka commented on Oct 20, 2026

    @tglowka
    Author

    App:

    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);
    }
    
  9. EgorBo commented on Oct 20, 2026

    @EgorBo
    Member

    anyway, this feels like handling/improving it on Regex level is something that will benefit everyrone I guess

  10. tglowka commented on Oct 21, 2026

    @tglowka
    Author

    Could you elaborate?

  11. eiriktsarpalis commented on Oct 21, 2026

    @eiriktsarpalis
    Member

    Egor is suggesting that making relevant improvements in the regex generator itself is preferable.

  12. tglowka commented on Oct 21, 2026

    @tglowka
    Author

    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) :

    | Method       | Case      | Mean      | Error     | StdDev    | Ratio | Allocated | Alloc Ratio |
    |------------- |---------- |----------:|----------:|----------:|------:|----------:|------------:|
    | IntegerRegex | AllDigits | 26.880 ns | 0.0051 ns | 0.0040 ns |  1.00 |         - |          NA |
    | IsInteger    | AllDigits |  5.971 ns | 0.0996 ns | 0.0831 ns |  0.22 |         - |          NA |
    | IsInteger2   | AllDigits |  4.192 ns | 0.0023 ns | 0.0021 ns |  0.16 |         - |          NA |
    |              |           |           |           |           |       |           |             |
    | IntegerRegex | IntShort  | 26.628 ns | 0.0393 ns | 0.0348 ns |  1.00 |         - |          NA |
    | IsInteger    | IntShort  |  2.060 ns | 0.0101 ns | 0.0090 ns |  0.08 |         - |          NA |
    | IsInteger2   | IntShort  |  3.883 ns | 0.0088 ns | 0.0082 ns |  0.15 |         - |          NA |
    |              |           |           |           |           |       |           |             |
    | IntegerRegex | Name      | 24.651 ns | 0.0500 ns | 0.0468 ns |  1.00 |         - |          NA |
    | IsInteger    | Name      |  1.711 ns | 0.0064 ns | 0.0059 ns |  0.07 |         - |          NA |
    | IsInteger2   | Name      |  2.608 ns | 0.0083 ns | 0.0078 ns |  0.11 |         - |          NA |
    |              |           |           |           |           |       |           |             |
    | IntegerRegex | Negative  | 26.580 ns | 0.0345 ns | 0.0322 ns |  1.00 |         - |          NA |
    | IsInteger    | Negative  |  2.416 ns | 0.0095 ns | 0.0089 ns |  0.09 |         - |          NA |
    | IsInteger2   | Negative  |  3.792 ns | 0.0071 ns | 0.0063 ns |  0.14 |         - |          NA |
    |              |           |           |           |           |       |           |             |
    | IntegerRegex | Overflow  | 26.808 ns | 0.0513 ns | 0.0480 ns |  1.00 |         - |          NA |
    | IsInteger    | Overflow  | 15.804 ns | 0.0157 ns | 0.0147 ns |  0.59 |         - |          NA |
    | IsInteger2   | Overflow  |  5.207 ns | 0.0137 ns | 0.0128 ns |  0.19 |         - |          NA |
    |              |           |           |           |           |       |           |             |
    | IntegerRegex | Padded    | 29.358 ns | 0.0579 ns | 0.0542 ns |  1.00 |         - |          NA |
    | IsInteger    | Padded    | 10.246 ns | 0.0025 ns | 0.0023 ns |  0.35 |         - |          NA |
    | IsInteger2   | Padded    |  7.987 ns | 0.0337 ns | 0.0299 ns |  0.27 |         - |          NA |
    

    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!

  13. EgorBo commented on Oct 21, 2026

    @EgorBo
    Member

    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.

    Perhaps it should be inlined then? 🤷

  14. tglowka commented on Oct 26, 2026

    @tglowka
    Author

    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

    I ran the following benchmark:

    [MemoryDiagnoser]
    [GenericTypeArguments(typeof(MyEnum60))] //public enum MyEnum60 { Value001 = 1, Value002 = 2, ..., Value060 = 60}
    [GenericTypeArguments(typeof(MyEnum61))] //public enum MyEnum61 { Value001 = 1, Value002 = 2, ..., Value061 = 61}
    [GenericTypeArguments(typeof(MyEnum100))] //public enum MyEnum100 { Value001 = 1, Value002 = 2, ..., Value100 = 100}
    public class RuntimeConcurrentDictionaryBenchmark<TEnum> where TEnum : struct, Enum
    {
        private const string Payload = "[\"1\", \"0\", \"+2\", \"3\"]";
        private readonly JsonSerializerOptions _opts = new() { Converters = { new JsonStringEnumConverter() } };
    
        [Benchmark]
        public TEnum[] Foo() => JsonSerializer.Deserialize<TEnum[]>(Payload, _opts)!;
    }
    

    and obtained the results:

    | Method | Enum | Mean (baseline) | Mean (counter) | Ratio |
    |--------|------|----------------:|---------------:|------:|
    | Foo    | Enum60  |   264.6 ns |  251.4 ns | 0.95 |
    | Foo    | Enum61  | 4,323.5 ns |  279.8 ns | 0.06 |
    | Foo    | Enum100 | 16,859.6 ns | 372.0 ns | 0.02 |
    

    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.

  15. EgorBo commented on Oct 27, 2026

    @EgorBo
    Member

    @tglowka want to file a PR with this improvement? I think it makes sense. (or I can try on your behalf if you want).

  16. tglowka commented on Oct 27, 2026

    @tglowka
    Author

    @EgorBo Sure thing, I will prepare a PR! The PR should point to this issue (or the other way around), right?

  17. EgorBo commented on Oct 27, 2026

    @EgorBo
    Member

    16. @EgorBo Sure thing, I will prepare a PR! The PR should point to this issue (or the other way around), right?

    I filed #136516, feel free to submit a PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.Jsonuntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions