Skip to content

Commit e63e3b7

Browse files
committed
Optimize hash code calculation for PooledString by limiting character processing
1 parent 5e52cda commit e63e3b7

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

PooledString.cs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -316,16 +316,32 @@ public readonly bool Equals(PooledString other)
316316
public override readonly int GetHashCode()
317317
{
318318
if (AllocationId == UnmanagedStringPool.EmptyStringAllocationId) {
319-
return 0; // Empty string has a hash code of 0
319+
return 0;
320320
}
321321

322322
if (Pool.IsDisposed) {
323323
return -1;
324324
}
325325

326+
const int maxChars = 64;
327+
const int halfMax = maxChars / 2;
328+
var span = AsSpan();
326329
var hash = new HashCode();
327-
foreach (var c in AsSpan()) {
328-
hash.Add(c);
330+
331+
if (span.Length <= maxChars) {
332+
// Hash all characters
333+
foreach (var c in span) {
334+
hash.Add(c);
335+
}
336+
} else {
337+
// Hash first fragment and last fragment chars
338+
foreach (var c in span[..halfMax]) {
339+
hash.Add(c);
340+
}
341+
342+
foreach (var c in span[^halfMax..]) {
343+
hash.Add(c);
344+
}
329345
}
330346

331347
return hash.ToHashCode();

0 commit comments

Comments
 (0)