Use SearchValues to scan for characters to escape with default Json options#129781
Merged
Conversation
This comment was marked as outdated.
This comment was marked as outdated.
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-text-json |
Contributor
There was a problem hiding this comment.
Pull request overview
This PR optimizes the “needs escaping?” scan in System.Text.Json’s writer helpers for the default encoding scenario by using SearchValues<T> + IndexOfAnyExcept (under #if NET) when no custom JavaScriptEncoder is provided.
Changes:
- Introduces
SearchValues<byte>/SearchValues<char>instances representing theAllowList-permitted ASCII set. - Uses
IndexOfAnyExcept(...)to find the first character/byte needing escaping whenencoder is null(NET builds), otherwise falls back toJavaScriptEncoder.FindFirstCharacterToEncode*.
Note: I did not build or run tests as part of this review.
Member
Author
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkSwitcher.FromAssembly(typeof(JsonWriteStrings).Assembly).Run(args);
// Targets JsonWriterHelper.NeedsEscaping(ReadOnlySpan<char|byte>, encoder), which this change routes
// through SearchValues for the default-escaping case. The fast path triggers when the encoder is null
// (default options) OR is the JavaScriptEncoder.Default singleton (ReferenceEquals). ExplicitDefaultEncoder
// toggles between those two so both branches are measured.
[MemoryDiagnoser]
public class JsonWriteStrings
{
public enum Escape { NoneEscaped, OneEscaped, AllEscaped }
[Params(Escape.NoneEscaped, Escape.OneEscaped, Escape.AllEscaped)]
public Escape Escaped;
[Params(false, true)]
public bool ExplicitDefaultEncoder;
private const int Count = 10_000;
private ArrayBufferWriter<byte> _buffer;
private JsonWriterOptions _options;
private string[] _utf16;
private byte[][] _utf8;
[GlobalSetup]
public void Setup()
{
_buffer = new ArrayBufferWriter<byte>();
_options = new JsonWriterOptions { Encoder = ExplicitDefaultEncoder ? JavaScriptEncoder.Default : null };
var rng = new Random(42);
_utf16 = new string[Count];
_utf8 = new byte[Count][];
for (int i = 0; i < Count; i++)
{
_utf16[i] = MakeString(rng, 5, 100, Escaped);
_utf8[i] = Encoding.UTF8.GetBytes(_utf16[i]);
}
}
private static string MakeString(Random rng, int min, int max, Escape escape)
{
int len = rng.Next(min, max);
var arr = new char[len];
if (escape == Escape.AllEscaped)
{
Array.Fill(arr, '"');
return new string(arr);
}
for (int i = 0; i < len; i++)
{
arr[i] = (char)rng.Next('a', 'z' + 1);
}
if (escape == Escape.OneEscaped)
{
arr[rng.Next(0, len)] = '"';
}
return new string(arr);
}
// UTF-16 (char) path -> NeedsEscaping(ReadOnlySpan<char>, encoder)
[Benchmark]
public void WriteStringValues_Utf16()
{
_buffer.Clear();
using var writer = new Utf8JsonWriter(_buffer, _options);
writer.WriteStartArray();
for (int i = 0; i < Count; i++)
{
writer.WriteStringValue(_utf16[i]);
}
writer.WriteEndArray();
writer.Flush();
}
// UTF-8 (byte) path -> NeedsEscaping(ReadOnlySpan<byte>, encoder)
[Benchmark]
public void WriteStringValues_Utf8()
{
_buffer.Clear();
using var writer = new Utf8JsonWriter(_buffer, _options);
writer.WriteStartArray();
for (int i = 0; i < Count; i++)
{
writer.WriteStringValue(_utf8[i]);
}
writer.WriteEndArray();
writer.Flush();
}
}
// End-to-end serialization (property names + ASCII string values), default encoder vs explicit Default.
[MemoryDiagnoser]
public class JsonSerializeStringHeavy
{
[Params(false, true)]
public bool ExplicitDefaultEncoder;
private JsonSerializerOptions _options;
private Dictionary<string, string> _dictionary;
private LoginViewModel _login;
[GlobalSetup]
public void Setup()
{
_options = new JsonSerializerOptions { Encoder = ExplicitDefaultEncoder ? JavaScriptEncoder.Default : null };
_dictionary = new Dictionary<string, string>();
for (int i = 0; i < 100; i++)
{
_dictionary["property_name_" + i] = "some string value number " + i;
}
_login = new LoginViewModel
{
Email = "name.familyname@not.com",
Password = "abcdefgh123456!@#$%^&*()",
RememberMe = true,
};
}
[Benchmark]
public byte[] Serialize_Dictionary() => JsonSerializer.SerializeToUtf8Bytes(_dictionary, _options);
[Benchmark]
public byte[] Serialize_Login() => JsonSerializer.SerializeToUtf8Bytes(_login, _options);
}
public class LoginViewModel
{
public string Email { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
}Note This benchmark comment was generated with assistance from GitHub Copilot. |
Member
Author
|
@MihuBot benchmark Perf_Strings -medium |
System.Text.Json.Tests.Perf_Strings
|
This was referenced Jun 24, 2026
eiriktsarpalis
approved these changes
Jun 24, 2026
Member
Author
@eiriktsarpalis mind taking another look please given the new restrictions? |
eiriktsarpalis
approved these changes
Jun 25, 2026
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.
Helps avoid some indirection in the common case.
A couple small improvements: EgorBot/Benchmarks#268 (comment), #129781 (comment)