Skip to content

Commit 09c8e88

Browse files
committed
Added info on (x << 5) + x over x * 33 optimization
1 parent c309019 commit 09c8e88

File tree

1 file changed

+5
-0
lines changed

1 file changed

+5
-0
lines changed

Microsoft.Toolkit.HighPerformance/Helpers/Internals/SpanHelper.Hash.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ public static unsafe int GetDjb2HashCode<T>(ref T r0, IntPtr length)
3131

3232
while ((byte*)length >= (byte*)8)
3333
{
34+
// Doing a left shift by 5 and adding is equivalent to multiplying by 33.
35+
// This is preferred for performance reasons, as when working with integer
36+
// values most CPUs have higher latency for multiplication operations
37+
// compared to a simple shift and add. For more info on this, see the
38+
// details for imul, shl, add: https://gmplib.org/~tege/x86-timing.pdf.
3439
hash = unchecked(((hash << 5) + hash) ^ Unsafe.Add(ref r0, offset + 0).GetHashCode());
3540
hash = unchecked(((hash << 5) + hash) ^ Unsafe.Add(ref r0, offset + 1).GetHashCode());
3641
hash = unchecked(((hash << 5) + hash) ^ Unsafe.Add(ref r0, offset + 2).GetHashCode());

0 commit comments

Comments
 (0)