-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Use global caching in JsonSerializerOptions #64646
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
eiriktsarpalis
merged 10 commits into
dotnet:main
from
eiriktsarpalis:member-accessor-caching
Feb 14, 2022
Merged
Changes from 1 commit
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
76c9069
Use caching in Reflection.Emit member accessors
eiriktsarpalis d1ffeaf
Refactor JsonSerializerOptions caching & use shared caching contexts
eiriktsarpalis fea5593
Update src/libraries/System.Text.Json/src/System/Text/Json/Serializat…
eiriktsarpalis 0e049e7
address feedback
eiriktsarpalis a2b8975
tweak cache eviction constants
eiriktsarpalis f9efaf9
Update src/libraries/System.Text.Json/src/System/Text/Json/Serializat…
eiriktsarpalis 801bf0b
minor refinements to cache eviction algorithm
eiriktsarpalis 5b917e2
rename JsonSerializerOptions._context to _serializerContext
eiriktsarpalis 761b2ad
ensure that the update handler clears the shared caching contexts
eiriktsarpalis 3d9e9e2
fix remark
eiriktsarpalis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next
Next commit
Use caching in Reflection.Emit member accessors
- Loading branch information
commit 76c90692025cadb5cea41fc2aff9a3a3047cb9f3
There are no files selected for viewing
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
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
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
87 changes: 87 additions & 0 deletions
87
.../src/System/Text/Json/Serialization/Metadata/ReflectionEmitCachingMemberAccessor.Cache.cs
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| #if NETFRAMEWORK || NETCOREAPP | ||
| using System.Collections.Concurrent; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics; | ||
| using System.Threading; | ||
|
|
||
| namespace System.Text.Json.Serialization.Metadata | ||
| { | ||
| internal sealed partial class ReflectionEmitCachingMemberAccessor | ||
| { | ||
| private sealed class Cache<TKey> where TKey : notnull | ||
| { | ||
| private int _lock; | ||
| private long _lastEvictedTicks; // tracks total number of invocations to the cache; can be allowed to overflow. | ||
| private readonly long _evictionIntervalTicks; // number of cache invocations needed before triggering an eviction run. | ||
| private readonly long _slidingExpirationTicks; // max timespan allowed for cache entries to remain inactive. | ||
| private readonly ConcurrentDictionary<TKey, CacheEntry> _cache = new(); | ||
|
|
||
| public Cache(TimeSpan slidingExpiration, TimeSpan evictionInterval) | ||
| { | ||
| _slidingExpirationTicks = slidingExpiration.Ticks; | ||
| _evictionIntervalTicks = evictionInterval.Ticks; | ||
| _lastEvictedTicks = DateTime.UtcNow.Ticks; | ||
| } | ||
|
|
||
| public TValue GetOrAdd<TValue>(TKey key, Func<TKey, TValue> valueFactory) where TValue : class? | ||
| { | ||
| CacheEntry entry = _cache.GetOrAdd(key, | ||
| #if NETCOREAPP | ||
| static (TKey key, Func<TKey, TValue> valueFactory) => new(valueFactory(key)), | ||
| valueFactory); | ||
| #else | ||
| key => new(valueFactory(key))); | ||
| #endif | ||
| long utcNowTicks = DateTime.UtcNow.Ticks; | ||
| Volatile.Write(ref entry.LastUsedTicks, utcNowTicks); | ||
|
|
||
| if (utcNowTicks - Volatile.Read(ref _lastEvictedTicks) > _evictionIntervalTicks) | ||
eiriktsarpalis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| if (Interlocked.CompareExchange(ref _lock, 1, 0) == 0) | ||
| { | ||
| if (utcNowTicks - _lastEvictedTicks >= _evictionIntervalTicks) | ||
| { | ||
| EvictStaleCacheEntries(utcNowTicks); | ||
| Volatile.Write(ref _lastEvictedTicks, utcNowTicks); | ||
| Volatile.Write(ref _lock, 0); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return (TValue)entry.Value!; | ||
| } | ||
|
|
||
| public void Clear() | ||
| { | ||
| _cache.Clear(); | ||
| _lastEvictedTicks = DateTime.UtcNow.Ticks; | ||
| } | ||
|
|
||
| private void EvictStaleCacheEntries(long utcNowTicks) | ||
| { | ||
| foreach (KeyValuePair<TKey, CacheEntry> kvp in _cache) | ||
| { | ||
| if (utcNowTicks - Volatile.Read(ref kvp.Value.LastUsedTicks) >= _slidingExpirationTicks) | ||
| { | ||
| _cache.TryRemove(kvp.Key, out _); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private class CacheEntry | ||
eiriktsarpalis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| public readonly object? Value; | ||
| public long LastUsedTicks; | ||
|
|
||
| public CacheEntry(object? value) | ||
| { | ||
| Value = value; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| #endif | ||
64 changes: 64 additions & 0 deletions
64
...t.Json/src/System/Text/Json/Serialization/Metadata/ReflectionEmitCachingMemberAccessor.cs
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| #if NETFRAMEWORK || NETCOREAPP | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Reflection; | ||
|
|
||
| namespace System.Text.Json.Serialization.Metadata | ||
| { | ||
| internal sealed partial class ReflectionEmitCachingMemberAccessor : MemberAccessor | ||
| { | ||
| private static readonly ReflectionEmitMemberAccessor s_sourceAccessor = new(); | ||
| private static readonly Cache<(string id, Type declaringType, MemberInfo? member)> s_cache = | ||
| new(slidingExpiration: TimeSpan.FromSeconds(5), evictionInterval: TimeSpan.FromSeconds(1)); | ||
eiriktsarpalis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| public static void Clear() => s_cache.Clear(); | ||
|
|
||
| public override Action<TCollection, object?> CreateAddMethodDelegate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] TCollection>() | ||
| => s_cache.GetOrAdd((nameof(CreateAddMethodDelegate), typeof(TCollection), null), | ||
| [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2091:UnrecognizedReflectionPattern", | ||
| Justification = "DynamicallyAccessedMembersAttribute is not inherited by scoped generic parameter in lambda body.")] | ||
| static (_) => s_sourceAccessor.CreateAddMethodDelegate<TCollection>()); | ||
|
|
||
| public override JsonTypeInfo.ConstructorDelegate? CreateConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type classType) | ||
| => s_cache.GetOrAdd((nameof(CreateConstructor), classType, null), | ||
| [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2077:UnrecognizedReflectionPattern", | ||
| Justification = "Cannot apply DynamicallyAccessedMembersAttribute to tuple properties.")] | ||
| static (key) => s_sourceAccessor.CreateConstructor(key.declaringType)); | ||
|
|
||
| public override Func<object, TProperty> CreateFieldGetter<TProperty>(FieldInfo fieldInfo) | ||
| => s_cache.GetOrAdd((nameof(CreateFieldGetter), typeof(TProperty), fieldInfo), static key => s_sourceAccessor.CreateFieldGetter<TProperty>((FieldInfo)key.member!)); | ||
|
|
||
| public override Action<object, TProperty> CreateFieldSetter<TProperty>(FieldInfo fieldInfo) | ||
| => s_cache.GetOrAdd((nameof(CreateFieldSetter), typeof(TProperty), fieldInfo), static key => s_sourceAccessor.CreateFieldSetter<TProperty>((FieldInfo)key.member!)); | ||
|
|
||
| [RequiresUnreferencedCode(IEnumerableConverterFactoryHelpers.ImmutableConvertersUnreferencedCodeMessage)] | ||
| public override Func<IEnumerable<KeyValuePair<TKey, TValue>>, TCollection> CreateImmutableDictionaryCreateRangeDelegate<TCollection, TKey, TValue>() | ||
| => s_cache.GetOrAdd((nameof(CreateImmutableDictionaryCreateRangeDelegate), typeof((TCollection, TKey, TValue)), null), | ||
| [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", | ||
| Justification = "Factory method calls into chained RequiresUnreferencedCode method.")] | ||
| static (_) => s_sourceAccessor.CreateImmutableDictionaryCreateRangeDelegate<TCollection, TKey, TValue>()); | ||
|
|
||
| [RequiresUnreferencedCode(IEnumerableConverterFactoryHelpers.ImmutableConvertersUnreferencedCodeMessage)] | ||
| public override Func<IEnumerable<TElement>, TCollection> CreateImmutableEnumerableCreateRangeDelegate<TCollection, TElement>() | ||
| => s_cache.GetOrAdd((nameof(CreateImmutableEnumerableCreateRangeDelegate), typeof((TCollection, TElement)), null), | ||
| [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", | ||
| Justification = "Factory method calls into chained RequiresUnreferencedCode method.")] | ||
| static (_) => s_sourceAccessor.CreateImmutableEnumerableCreateRangeDelegate<TCollection, TElement>()); | ||
|
|
||
| public override Func<object[], T>? CreateParameterizedConstructor<T>(ConstructorInfo constructor) | ||
| => s_cache.GetOrAdd((nameof(CreateParameterizedConstructor), typeof(T), constructor), static key => s_sourceAccessor.CreateParameterizedConstructor<T>((ConstructorInfo)key.member!)); | ||
|
|
||
| public override JsonTypeInfo.ParameterizedConstructorDelegate<T, TArg0, TArg1, TArg2, TArg3>? CreateParameterizedConstructor<T, TArg0, TArg1, TArg2, TArg3>(ConstructorInfo constructor) | ||
| => s_cache.GetOrAdd((nameof(CreateParameterizedConstructor), typeof(T), constructor), static key => s_sourceAccessor.CreateParameterizedConstructor<T, TArg0, TArg1, TArg2, TArg3>((ConstructorInfo)key.member!)); | ||
|
|
||
| public override Func<object, TProperty> CreatePropertyGetter<TProperty>(PropertyInfo propertyInfo) | ||
| => s_cache.GetOrAdd((nameof(CreatePropertyGetter), typeof(TProperty), propertyInfo), static key => s_sourceAccessor.CreatePropertyGetter<TProperty>((PropertyInfo)key.member!)); | ||
|
|
||
| public override Action<object, TProperty> CreatePropertySetter<TProperty>(PropertyInfo propertyInfo) | ||
| => s_cache.GetOrAdd((nameof(CreatePropertySetter), typeof(TProperty), propertyInfo), static key => s_sourceAccessor.CreatePropertySetter<TProperty>((PropertyInfo)key.member!)); | ||
| } | ||
| } | ||
| #endif | ||
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.
Uh oh!
There was an error while loading. Please reload this page.