Skip to content

Commit 4db776b

Browse files
committed
Minor perf improvements.
1 parent c1953f3 commit 4db776b

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

src/Autofac/Core/KeyedServiceParameterInjector.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,22 @@ public static IEnumerable<Parameter> AddKeyedServiceParameter(object serviceKey,
9696

9797
private static bool HasKeyParameter(IEnumerable<Parameter> parameters, object serviceKey)
9898
{
99+
if (parameters is IReadOnlyList<Parameter> readOnlyList)
100+
{
101+
if (readOnlyList.Count == 0)
102+
{
103+
return false;
104+
}
105+
106+
// Fast path for the common case where the key parameter is last.
107+
var lastIndex = readOnlyList.Count - 1;
108+
if (readOnlyList[lastIndex] is KeyedServiceKeyParameter lastKey &&
109+
Equals(lastKey.ServiceKey, serviceKey))
110+
{
111+
return true;
112+
}
113+
}
114+
99115
foreach (var parameter in parameters)
100116
{
101117
if (parameter is KeyedServiceKeyParameter keyParameter && Equals(keyParameter.ServiceKey, serviceKey))

src/Autofac/ParameterExtensions.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,12 @@ public static T KeyedServiceKey<T>(this IEnumerable<Parameter> parameters)
103103
throw new ArgumentNullException(nameof(parameters));
104104
}
105105

106-
var keyParameter = parameters.OfType<KeyedServiceKeyParameter>().FirstOrDefault();
107-
if (keyParameter is not null)
106+
foreach (var parameter in parameters)
108107
{
109-
return (T)keyParameter.ServiceKey;
108+
if (parameter is KeyedServiceKeyParameter keyParameter)
109+
{
110+
return (T)keyParameter.ServiceKey;
111+
}
110112
}
111113

112114
throw new InvalidOperationException(ResolutionExtensionsResources.KeyedServiceKeyUnavailable);

0 commit comments

Comments
 (0)