Skip to content

Commit

Permalink
Hashing (#161)
Browse files Browse the repository at this point in the history
* Added benchmark for murmur hash vs system `HashCode`

* The benchmark shows that `HashCode` is faster than murmurhash3:

```
|     Method |     N |       Mean |   Error |  StdDev |
|----------- |------ |-----------:|--------:|--------:|
| MurmurHash |  1000 |   209.1 ns | 0.11 ns | 0.11 ns |
|   HashCode |  1000 |   133.8 ns | 0.18 ns | 0.17 ns |
| MurmurHash | 10000 | 2,117.4 ns | 2.74 ns | 2.43 ns |
|   HashCode | 10000 | 1,349.3 ns | 2.95 ns | 2.62 ns |
```

Based on this removed MurmurHash3.cs entirely and replaced all uses with `HashCode`.
  • Loading branch information
martindevans authored Oct 28, 2023
1 parent 56b1641 commit b5fa959
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 74 deletions.
26 changes: 26 additions & 0 deletions src/Arch/Core/Extensions/Internal/HashCodeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace Arch.Core.Extensions.Internal;

internal static class HashCodeExtensions
{
#if !NET5_0_OR_GREATER
public static void AddBytes(ref this HashCode hashCode, ReadOnlySpan<byte> bytes)
{
for (int i = 0; i < bytes.Length; i++)
{
hashCode.Add(bytes[i]);
}
}
#endif

public static void AddSpan<T>(ref this HashCode hashCode, ReadOnlySpan<T> items)
where T : unmanaged
{
hashCode.AddBytes(MemoryMarshal.AsBytes(items));
}

public static void AddSpan<T>(ref this HashCode hashCode, Span<T> items)
where T : unmanaged
{
hashCode.AddBytes(MemoryMarshal.AsBytes(items));
}
}
11 changes: 3 additions & 8 deletions src/Arch/Core/Utils/CompileTimeStatics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -455,17 +455,12 @@ public static int GetHashCode(Span<ComponentType> obj)
return GetHashCode(stack);
}

/// <summary>
/// Calculates the hash code of a bitset span, which is unique for the elements contained in the array.
/// The order of the elements does not change the hashcode, so it depends on the elements themselves.
/// </summary>
/// <param name="obj">The <see cref="BitSet"/>.</param>
/// <returns>A unique hashcode for the contained elements, regardless of their order.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetHashCode(Span<uint> span)
{
var bytes = MemoryMarshal.AsBytes(span);
return (int)MurmurHash3.Hash32(bytes, 0);
var hashCode = new HashCode();
hashCode.AddSpan(span);
return hashCode.ToHashCode();
}
}

Expand Down
66 changes: 0 additions & 66 deletions src/Arch/Core/Utils/MurmurHash3.cs

This file was deleted.

0 comments on commit b5fa959

Please sign in to comment.