Skip to content

Commit 9cfb133

Browse files
Reduce allocations due to LINQ and string building. (#28467)
* Reduce allocations due to LINQ and string building. * Update src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs Co-authored-by: Pranav K <[email protected]>
1 parent 8df66d1 commit 9cfb133

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

src/HealthChecks/HealthChecks/src/DefaultHealthCheckService.cs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -158,15 +158,23 @@ private async Task<HealthReportEntry> RunCheckAsync(IServiceScope scope, HealthC
158158
private static void ValidateRegistrations(IEnumerable<HealthCheckRegistration> registrations)
159159
{
160160
// Scan the list for duplicate names to provide a better error if there are duplicates.
161-
var duplicateNames = registrations
162-
.GroupBy(c => c.Name, StringComparer.OrdinalIgnoreCase)
163-
.Where(g => g.Count() > 1)
164-
.Select(g => g.Key)
165-
.ToList();
166161

167-
if (duplicateNames.Count > 0)
162+
StringBuilder? builder = null;
163+
var distinctRegistrations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
164+
165+
foreach (var registration in registrations)
166+
{
167+
if (!distinctRegistrations.Add(registration.Name))
168+
{
169+
builder ??= new StringBuilder("Duplicate health checks were registered with the name(s): ");
170+
171+
builder.Append(registration.Name).Append(", ");
172+
}
173+
}
174+
175+
if (builder is not null)
168176
{
169-
throw new ArgumentException($"Duplicate health checks were registered with the name(s): {string.Join(", ", duplicateNames)}", nameof(registrations));
177+
throw new ArgumentException(builder.ToString(0, builder.Length - 2), nameof(registrations));
170178
}
171179
}
172180

0 commit comments

Comments
 (0)