Avoid duplicate PropertyRef[] allocation in UTF-8 property cache publish#130656
Merged
eiriktsarpalis merged 2 commits intoJul 14, 2026
Merged
Conversation
UpdateUtf8PropertyCache called cacheBuilder.ToArray() twice, allocating two identical PropertyRef[] arrays and discarding the first. Store the result once and reuse it for both the length assertion and the cache assignment. Behavior is unchanged; only the redundant allocation is removed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: e3f810bd-cfc7-4046-84ce-23318cf5d1a3
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-text-json |
Contributor
There was a problem hiding this comment.
Pull request overview
Removes a redundant PropertyRef[] allocation when publishing JsonTypeInfo’s UTF-8 property-name cache by reusing the already-materialized array rather than calling PropertyRefCacheBuilder.ToArray() twice.
Changes:
- Reuse
newCachefor_utf8PropertyCachepublication instead of allocating/publishing a second identical array. - Preserve the existing capacity invariant check (
Debug.Assert(newCache.Length <= PropertyRefCacheBuilder.MaxCapacity)).
Show a summary per file
| File | Description |
|---|---|
| src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.Cache.cs | Publishes the already-created PropertyRef[] (newCache) to avoid a duplicate ToArray() allocation during cache update. |
Copilot's findings
- Files reviewed: 1/1 changed files
- Comments generated: 0
Member
|
This change looks good to have even if the perf numbers don't reflect it. The previous code is wastefully allocating an extra array. |
Member
Author
|
@EgorBot -intel -arm using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using BenchmarkDotNet.Attributes;
[MemoryDiagnoser]
public class JsonUtf8CachePublish
{
private readonly byte[] _utf8 = Encoding.UTF8.GetBytes(
"{\"A\":1,\"B\":\"b\",\"C\":\"c\",\"D\":4,\"E\":true,\"F\":6.0,\"G\":\"g\"}");
// Fresh DefaultJsonTypeInfoResolver per op defeats STJ's options-equality
// metadata caching, forcing a genuine UTF-8 property-cache publish each op.
[Benchmark]
public Poco Deserialize_FreshResolver()
{
var options = new JsonSerializerOptions { TypeInfoResolver = new DefaultJsonTypeInfoResolver() };
return JsonSerializer.Deserialize<Poco>(_utf8, options)!;
}
public sealed class Poco
{
public int A { get; set; }
public string? B { get; set; }
public string? C { get; set; }
public int D { get; set; }
public bool E { get; set; }
public double F { get; set; }
public string? G { get; set; }
}
}Note Benchmark request drafted with assistance from GitHub Copilot. |
eiriktsarpalis
approved these changes
Jul 14, 2026
|
Azure Pipelines: Successfully started running 3 pipeline(s). 12 pipeline(s) were filtered out due to trigger conditions. There may be pipelines that require an authorized user to comment /azp run to run. |
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.
JsonTypeInfo.UpdateUtf8PropertyCachecallscacheBuilder.ToArray()twice: itbuilds the
PropertyRef[], asserts its length, then builds a second identicalarray and publishes that one, discarding the first.
ToArray()allocates a fresh array each call and the builder isn't mutated betweenthe two calls, so the arrays are identical — behavior is unchanged and one
PropertyRef[]allocation per cache publish is removed.Measured allocation impact
Allocation per UTF-8 property-cache publish, forcing a fresh
JsonTypeInfo(newDefaultJsonTypeInfoResolver) per deserialize so the publish path runs each op.GC.GetAllocatedBytesForCurrentThread, 20,000 iters × 7 reps, .NET 11 preview, arm64:Each row's saving is exactly one eliminated
PropertyRef[N](24 B array header +N × 24 B
PropertyRefstructs), scaling with the type's property count.This is a publish/warm-up-path saving, bounded per
JsonTypeInfo— STJ pools cachingcontexts by options-equality, so steady-state repeated-serialization benchmarks show
it amortized to ~0/op. No steady-state or per-request regression or gain is claimed.
Validation
ordering, case-insensitivity, duplicate-property handling, escaping, and exception
paths as before — only the redundant second allocation is removed.
Concurrency
UpdateUtf8PropertyCacheis optimistic last-writer-wins. The losing-race path(
currentCache != cacheBuilder.OriginalCache) publishes nothing and allocatesneither array — in both baseline and fixed. This change only touches the winning
path, removing one duplicate array there.
7-property type through one shared options instance) showed 0 correctness mismatches
and 0 exceptions on both baseline and fixed.
GC.GetAllocatedBytesForCurrentThreadis thread-local, so the concurrencyprobe validates correctness, not per-op bytes; the allocation figures above come
from the single-threaded probe.
Note
This PR description was drafted with assistance from GitHub Copilot.