Skip to content

Commit a734aa4

Browse files
Remove per-context delegate allocations in netcoreapp targets (#80517)
* Remove per-context delegate allocations in netcoreapp targets * Ensure Options property doesn't get trimmed.
1 parent 1c8b2de commit a734aa4

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.Caching.cs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -156,14 +156,17 @@ internal void ClearCaches()
156156
internal sealed class CachingContext
157157
{
158158
private readonly ConcurrentDictionary<Type, JsonTypeInfo?> _jsonTypeInfoCache = new();
159+
#if !NETCOREAPP
159160
private readonly Func<Type, JsonTypeInfo?> _jsonTypeInfoFactory;
161+
#endif
160162

161163
public CachingContext(JsonSerializerOptions options, int hashCode)
162164
{
163165
Options = options;
164166
HashCode = hashCode;
165-
166-
_jsonTypeInfoFactory = options.GetTypeInfoNoCaching;
167+
#if !NETCOREAPP
168+
_jsonTypeInfoFactory = Options.GetTypeInfoNoCaching;
169+
#endif
167170
}
168171

169172
public JsonSerializerOptions Options { get; }
@@ -172,7 +175,12 @@ public CachingContext(JsonSerializerOptions options, int hashCode)
172175
// If changing please ensure that src/ILLink.Descriptors.LibraryBuild.xml is up-to-date.
173176
public int Count => _jsonTypeInfoCache.Count;
174177

175-
public JsonTypeInfo? GetOrAddJsonTypeInfo(Type type) => _jsonTypeInfoCache.GetOrAdd(type, _jsonTypeInfoFactory);
178+
public JsonTypeInfo? GetOrAddJsonTypeInfo(Type type) =>
179+
#if NETCOREAPP
180+
_jsonTypeInfoCache.GetOrAdd(type, static (type, options) => options.GetTypeInfoNoCaching(type), Options);
181+
#else
182+
_jsonTypeInfoCache.GetOrAdd(type, _jsonTypeInfoFactory);
183+
#endif
176184

177185
public bool TryGetJsonTypeInfo(Type type, [NotNullWhen(true)] out JsonTypeInfo? typeInfo) => _jsonTypeInfoCache.TryGetValue(type, out typeInfo);
178186

0 commit comments

Comments
 (0)