Skip to content

Commit 3e7382e

Browse files
authored
Avoid some allocations in BitVector256 (#120427)
Avoid eight unnecessary allocations (the list, plus seven internal arrays due to resizing).
1 parent f3c990f commit 3e7382e

File tree

1 file changed

+10
-6
lines changed
  • src/libraries/System.Private.CoreLib/src/System/SearchValues

1 file changed

+10
-6
lines changed

src/libraries/System.Private.CoreLib/src/System/SearchValues/BitVector256.cs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,28 +50,32 @@ private readonly bool ContainsUnchecked(int b)
5050

5151
public readonly char[] GetCharValues()
5252
{
53-
var chars = new List<char>();
53+
Span<char> chars = stackalloc char[256];
54+
int size = 0;
5455
for (int i = 0; i < 256; i++)
5556
{
5657
if (ContainsUnchecked(i))
5758
{
58-
chars.Add((char)i);
59+
chars[size] = (char)i;
60+
size++;
5961
}
6062
}
61-
return chars.ToArray();
63+
return chars.Slice(0, size).ToArray();
6264
}
6365

6466
public readonly byte[] GetByteValues()
6567
{
66-
var bytes = new List<byte>();
68+
Span<byte> bytes = stackalloc byte[256];
69+
int size = 0;
6770
for (int i = 0; i < 256; i++)
6871
{
6972
if (ContainsUnchecked(i))
7073
{
71-
bytes.Add((byte)i);
74+
bytes[size] = (byte)i;
75+
size++;
7276
}
7377
}
74-
return bytes.ToArray();
78+
return bytes.Slice(0, size).ToArray();
7579
}
7680
}
7781
}

0 commit comments

Comments
 (0)