Skip to content

Commit eec0d42

Browse files
committed
Optimize IsList() check to only call GetGenericTypeDefinition() once
It's likely that `GetGenericTypeDefinition()` is a fast call that's cached by the framework. Nevertheless, there's no reason to call it three times in a row. A faster approach is to simply place the types in a static collection and then check to see if that collection contains the `GetGenericTypeDefinition()`.
1 parent b745768 commit eec0d42

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

OnTopic/Mapping/TopicMappingService.cs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,19 @@ public class TopicMappingService : ITopicMappingService {
3030
\-------------------------------------------------------------------------------------------------------------------------*/
3131
readonly ITopicRepository _topicRepository;
3232
readonly ITypeLookupService _typeLookupService;
33+
static readonly List<Type> _listTypes = new();
34+
35+
/*==========================================================================================================================
36+
| CONSTRUCTOR
37+
\-------------------------------------------------------------------------------------------------------------------------*/
38+
/// <summary>
39+
/// Establishes a new instance of a <see cref="TopicMappingService"/> with required dependencies.
40+
/// </summary>
41+
static TopicMappingService() {
42+
_listTypes.Add(typeof(IEnumerable<>));
43+
_listTypes.Add(typeof(ICollection<>));
44+
_listTypes.Add(typeof(IList<>));
45+
}
3346

3447
/*==========================================================================================================================
3548
| CONSTRUCTOR
@@ -667,12 +680,7 @@ await MapAsync(
667680
/// <param name="targetType">The <see cref="Type"/> of collection to initialize.</param>
668681
private static bool IsList(Type targetType) =>
669682
typeof(IList).IsAssignableFrom(targetType) ||
670-
targetType.IsGenericType &&
671-
(
672-
targetType.GetGenericTypeDefinition() == typeof(IEnumerable<>) ||
673-
targetType.GetGenericTypeDefinition() == typeof(ICollection<>) ||
674-
targetType.GetGenericTypeDefinition() == typeof(IList<>)
675-
);
683+
targetType.IsGenericType && _listTypes.Contains(targetType.GetGenericTypeDefinition());
676684

677685
/*==========================================================================================================================
678686
| PRIVATE: INITIALIZE COLLECTION

0 commit comments

Comments
 (0)