Skip to content

Commit

Permalink
Use bytes for hash code generation instead of creating string and cal…
Browse files Browse the repository at this point in the history
…culate hash code from string object
  • Loading branch information
AlexanderN committed Feb 15, 2023
1 parent 1ea665e commit fe27a05
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/Combination.StringPools/PooledUtf8String.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public override bool Equals(object? obj)
}

public override int GetHashCode()
=> unchecked((int)StringHash.Compute(Utf8StringPool.Get(handle)));
=> unchecked((int)StringHash.Compute(Utf8StringPool.GetBytes(handle)));

public override string ToString() => Utf8StringPool.Get(handle);

Expand Down
14 changes: 12 additions & 2 deletions src/Combination.StringPools/Utf8StringPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,16 @@ public static string Get(ulong handle)
return string.Empty;
}

return Encoding.UTF8.GetString(GetBytes(handle));
}

public static ReadOnlySpan<byte> GetBytes(ulong handle)
{
if (handle == ulong.MaxValue)
{
return Array.Empty<byte>();
}

var poolIndex = handle >> (64 - PoolIndexBits);
if (poolIndex >= (ulong)Pools.Count)
{
Expand All @@ -283,7 +293,7 @@ public static string Get(ulong handle)
}

[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private string GetFromPool(ulong handle)
private ReadOnlySpan<byte> GetFromPool(ulong handle)
{
using (disposeLock.PreventDispose())
{
Expand All @@ -296,7 +306,7 @@ private string GetFromPool(ulong handle)
throw new InvalidOperationException($"Internal error: Deduplicated string pool mismatch ({index} != {poolIndex})");
}
#endif
return Encoding.UTF8.GetString(GetStringBytes(offset));
return GetStringBytes(offset);
}
}

Expand Down

0 comments on commit fe27a05

Please sign in to comment.