Skip to content

Correct small inefficiency in private internal function in EFCore - FindIndexerPropertyInfo #34823

@yinzara

Description

@yinzara

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.

Metadata

Metadata

Type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions