Skip to content

Commit 687c8d9

Browse files
Henr1k80tarekghjkotas
authored
Array.FindAll improvements (#120336)
Now a small amount of matches are stack allocated and the array is only optionally allocated. --------- Co-authored-by: Tarek Mahmoud Sayed <[email protected]> Co-authored-by: Jan Kotas <[email protected]>
1 parent 833e132 commit 687c8d9

File tree

1 file changed

+17
-5
lines changed
  • src/libraries/System.Private.CoreLib/src/System

1 file changed

+17
-5
lines changed

src/libraries/System.Private.CoreLib/src/System/Array.cs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1553,15 +1553,27 @@ public static T[] FindAll<T>(T[] array, Predicate<T> match)
15531553
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
15541554
}
15551555

1556-
List<T> list = new List<T>();
1557-
for (int i = 0; i < array.Length; i++)
1556+
InlineArray4<T> stackAllocatedMatches = default;
1557+
Span<T> span = stackAllocatedMatches;
1558+
int foundCount = 0;
1559+
T[]? values = null;
1560+
1561+
foreach (T value in array)
15581562
{
1559-
if (match(array[i]))
1563+
if (match(value))
15601564
{
1561-
list.Add(array[i]);
1565+
if (foundCount >= span.Length)
1566+
{
1567+
values = new T[Math.Min((uint)span.Length * 2, (uint)array.Length)];
1568+
span.CopyTo(values);
1569+
span = values;
1570+
}
1571+
1572+
span[foundCount++] = value;
15621573
}
15631574
}
1564-
return list.ToArray();
1575+
1576+
return values?.Length == foundCount ? values : span[..foundCount].ToArray();
15651577
}
15661578

15671579
public static int FindIndex<T>(T[] array, Predicate<T> match)

0 commit comments

Comments
 (0)