Skip to content

Commit 0c317a6

Browse files
committed
optimize
more optimal algorithm
1 parent 1af187b commit 0c317a6

File tree

1 file changed

+11
-16
lines changed

1 file changed

+11
-16
lines changed

MurmurHash/Managed/Murmur32ManagedX86.cs

+11-16
Original file line numberDiff line numberDiff line change
@@ -25,28 +25,23 @@ protected override void HashCore(byte[] array, int ibStart, int cbSize)
2525
{
2626
Length += cbSize;
2727
if (cbSize > 0)
28-
{
29-
var blocks = (cbSize / 4);
30-
var remainder = (cbSize & 3);
31-
32-
Body(array, ibStart, blocks, remainder);
33-
}
28+
Body(array, ibStart, cbSize);
3429
}
3530

3631
[MethodImpl(MethodImplOptions.AggressiveInlining)]
37-
private void Body(byte[] data, int offset, int blocks, int remainder)
32+
private void Body(byte[] data, int start, int length)
3833
{
39-
// grab reference to the end of our data as uint blocks
40-
while (blocks-- > 0)
41-
{
42-
// get our values
43-
uint k1 = BitConverter.ToUInt32(data, offset); offset += 4;
34+
int remainder = length & 3;
35+
int alignedLength = start + (length - remainder);
4436

37+
for (int i = start; i < alignedLength; i += 4)
38+
{
39+
uint k1 = BitConverter.ToUInt32(data, i);
4540
H1 = (((H1 ^ (((k1 * C1).RotateLeft(15)) * C2)).RotateLeft(13)) * 5) + 0xe6546b64;
4641
}
4742

4843
if (remainder > 0)
49-
Tail(data, offset, remainder);
44+
Tail(data, alignedLength, remainder);
5045
}
5146

5247
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -58,9 +53,9 @@ private void Tail(byte[] tail, int position, int remainder)
5853
// determine how many bytes we have left to work with based on length
5954
switch (remainder)
6055
{
61-
case 3: k1 ^= (uint)tail[position + 2] << 16; goto case 2;
62-
case 2: k1 ^= (uint)tail[position + 1] << 8; goto case 1;
63-
case 1: k1 ^= tail[position]; break;
56+
case 3: k1 ^= (uint)tail[position + 2] << 16; goto case 2;
57+
case 2: k1 ^= (uint)tail[position + 1] << 8; goto case 1;
58+
case 1: k1 ^= tail[position]; break;
6459
}
6560

6661
H1 = H1 ^ ((k1 * C1).RotateLeft(15) * C2);

0 commit comments

Comments
 (0)