-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Description
While reading the codebase of Efcore I noticed a small inefficiency in a function used extensively throughout Efcore and I thought it was probably worth addressing.
Efcore/Metadata/RuntimeModel.cs -> Line 295
private PropertyInfo? FindIndexerPropertyInfo([DynamicallyAccessedMembers(IEntityType.DynamicallyAccessedMemberTypes)] Type type)
=> _indexerPropertyInfoMap.GetOrAdd(type, type.FindIndexerProperty());
In the above code, though the _indexerPropertyMap
is used to ensure we get the same indexer for the same type, because we're calling type.FindIndexerProperty()
we're not getting much benefit from it because the FindIndexerProperty
function is run no matter if there is a key found or not.
The GetOrAdd
function of the ConcurrentDictionary has an overload that accepts a Func<TKey, TValue>
factory method specifically for this purpose.
If we instead change the function to the following:
private PropertyInfo? FindIndexerPropertyInfo([DynamicallyAccessedMembers(IEntityType.DynamicallyAccessedMemberTypes)] Type type)
=> _indexerPropertyInfoMap.GetOrAdd(type, EntityFrameworkCore.Internal.TypeExtensions.FindIndexerProperty);
We use the overload that accepts the Func<TKey, TValue>
and only call the function if the key was not found in the map.