[EXPERIMENT] System.Text.Json: Performance optimizations for hot paths#124427
Draft
artl93 wants to merge 1 commit intodotnet:mainfrom
Draft
[EXPERIMENT] System.Text.Json: Performance optimizations for hot paths#124427artl93 wants to merge 1 commit intodotnet:mainfrom
artl93 wants to merge 1 commit intodotnet:mainfrom
Conversation
- Replace IntegerRegex with manual char scanning in enum parsing for faster integer detection in TryParseEnumFromString - Add AggressiveInlining to ValidateWritingValue and SetFlagToAddListSeparatorBeforeNextItem in Utf8JsonWriter (called on every value write) - Replace Delimiters.Contains() linear search with inline IsDelimiter() switch in number parsing hot paths (Utf8JsonReader and MultiSegment) - Replace EscapableChars.IndexOf() linear search with inline IsEscapableChar() switch in string escape validation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-text-json |
Member
Author
|
@EgorBot -amd -arm using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Text.Json;
using System.Text.Json.Serialization;
BenchmarkSwitcher.FromAssembly(typeof(Bench).Assembly).Run(args);
public enum Color { Red, Green, Blue, Yellow, Cyan, Magenta, White, Black }
public class SmallPoco
{
public int Id { get; set; }
public string Name { get; set; } = "";
public bool Active { get; set; }
public double Score { get; set; }
}
[MemoryDiagnoser]
public class Bench
{
private byte[] _smallJson = default!;
private byte[] _nestedJson = default!;
private byte[] _numberHeavyJson = default!;
private JsonSerializerOptions _enumOptions = default!;
[GlobalSetup]
public void Setup()
{
_smallJson = JsonSerializer.SerializeToUtf8Bytes(
new SmallPoco { Id = 42, Name = "test", Active = true, Score = 3.14 });
_nestedJson = JsonSerializer.SerializeToUtf8Bytes(
new { a = new { b = 1, c = "hello\nworld" }, d = new[] { 1, 2, 3 }, e = true, f = 0.0 });
_numberHeavyJson = System.Text.Encoding.UTF8.GetBytes("[0, 0.1, 0.123, 1, 12, 123, 1234, 12345, 0.999, 1.0e10]");
_enumOptions = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } };
}
[Benchmark]
public void Reader_SmallPoco()
{
var reader = new Utf8JsonReader(_smallJson);
while (reader.Read()) { }
}
[Benchmark]
public void Reader_NestedWithEscapes()
{
var reader = new Utf8JsonReader(_nestedJson);
while (reader.Read()) { }
}
[Benchmark]
public void Reader_NumberHeavy()
{
var reader = new Utf8JsonReader(_numberHeavyJson);
while (reader.Read()) { }
}
[Benchmark]
public byte[] Writer_SmallPoco()
{
return JsonSerializer.SerializeToUtf8Bytes(
new SmallPoco { Id = 42, Name = "test", Active = true, Score = 3.14 });
}
[Benchmark]
public Color Deserialize_Enum_String()
{
return JsonSerializer.Deserialize<Color>("\"Blue\"", _enumOptions);
}
[Benchmark]
public SmallPoco Deserialize_SmallPoco()
{
return JsonSerializer.Deserialize<SmallPoco>(_smallJson)!;
}
} |
Contributor
There was a problem hiding this comment.
Pull request overview
This experimental PR explores performance optimizations in System.Text.Json hot paths through three targeted changes: replacing span-based character lookups with switch expressions, adding aggressive inlining hints to frequently-called writer methods, and substituting regex validation with manual character scanning in the enum converter.
Changes:
- Reader optimizations: Replace
Delimiters.Contains()andEscapableChars.IndexOf()linear scans withIsDelimiter()andIsEscapableChar()switch expressions at 8 call sites - Writer optimizations: Add
AggressiveInliningtoValidateWritingValue()andSetFlagToAddListSeparatorBeforeNextItem() - Enum converter: Replace
JsonHelpers.IntegerRegex.IsMatch()with manualIsIntegerLike()character loop
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| src/libraries/System.Text.Json/src/System/Text/Json/JsonConstants.cs | Adds IsDelimiter() and IsEscapableChar() switch expression helpers with aggressive inlining to replace span linear searches |
| src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs | Replaces 3 Delimiters.Contains() and 1 EscapableChars.IndexOf() calls with new switch expression helpers |
| src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs | Replaces 4 Delimiters.Contains() and 2 EscapableChars.IndexOf() calls with new switch expression helpers |
| src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs | Adds AggressiveInlining attribute to SetFlagToAddListSeparatorBeforeNextItem() |
| src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.WriteValues.Helpers.cs | Adds AggressiveInlining attribute to ValidateWritingValue() |
| src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs | Replaces regex-based integer detection with manual IsIntegerLike() character loop |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This is an experimental performance exploration PR to validate speculative optimizations with EgorBot benchmarks. Please do not merge.
Changes
Reader: Inline delimiter/escape checks — Replace
Delimiters.Contains()(8-byte span scan) withIsDelimiter()switch expression in 5 hot-path call sites. Same forEscapableChars.IndexOf()→IsEscapableChar()(3 call sites).Writer: AggressiveInlining — Add
[MethodImpl(MethodImplOptions.AggressiveInlining)]toValidateWritingValue()andSetFlagToAddListSeparatorBeforeNextItem().Enum converter: Regex → manual char scan — Replace
JsonHelpers.IntegerRegex.IsMatch()withIsIntegerLike()loop inEnumConverter.Validation
Full audit report: https://gist.github.com/artl93/8f375461b1a29d48b26053b88db76058