From efea5ac7a2ac25e8bcbe292c4bac7c982ab2bb36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Thu, 12 Mar 2026 16:03:40 +0100 Subject: [PATCH] Optimize CollectionAssert: hoist GetTypeInfo() and avoid redundant enumerations - AllItemsAreInstancesOfType: Move expectedType.GetTypeInfo() outside the loop since it is loop-invariant, avoiding a redundant call per collection element. - AreNotEquivalent: Cache Count() results in local variables instead of calling Count() and then Any() separately, eliminating a third full enumeration of the collection. - AreEquivalent: Replace Any() call with a check against the already-cached count variable. --- .../TestFramework/Assertions/CollectionAssert.cs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs index 6be196fa94..c8f37e098b 100644 --- a/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs +++ b/src/TestFramework/TestFramework/Assertions/CollectionAssert.cs @@ -504,7 +504,7 @@ public static void AreEquivalent( } // If both collections are empty, they are equivalent. - if (!expected.Any()) + if (expectedCollectionCount == 0) { return; } @@ -661,13 +661,15 @@ public static void AreNotEquivalent( DebugEx.Assert(notExpected is not null, "expected is not null here"); // Check whether the element counts are different. - if (notExpected.Count() != actual.Count()) + int notExpectedCount = notExpected.Count(); + int actualCount = actual.Count(); + if (notExpectedCount != actualCount) { return; } // If both collections are empty, they are equivalent. - if (!notExpected.Any()) + if (notExpectedCount == 0) { string userMessage = Assert.BuildUserMessage(message); string finalMessage = string.Format( @@ -743,9 +745,8 @@ public static void AllItemsAreInstancesOfType( int i = 0; foreach (object? element in collection) { - if (expectedType.GetTypeInfo() is { } expectedTypeInfo - && element?.GetType().GetTypeInfo() is { } elementTypeInfo - && !expectedTypeInfo.IsAssignableFrom(elementTypeInfo)) + if (element?.GetType() is { } elementType + && !expectedType.IsAssignableFrom(elementType)) { string userMessage = Assert.BuildUserMessage(message); string finalMessage = string.Format(