【问题标题】:What is the best algorithm for overriding GetHashCode?覆盖 GetHashCode 的最佳算法是什么?
【发布时间】:2010-09-20 18:35:48
【问题描述】:

在 .NET 中,GetHashCode method 在整个 .NET 基类库中的很多地方都使用。正确实施它对于在集合中快速查找项目或在确定相等性时尤为重要。

是否有关于如何为我的自定义类实现 GetHashCode 以免降低性能的标准算法或最佳实践?

【问题讨论】:

  • 在阅读了这个问题和下面的文章之后,我可以实现GetHashCode 的覆盖。我希望它对其他人有帮助。 Guidelines and rules for GetHashCode written by Eric Lippert
  • “或确定相等”:不!具有相同哈希码的两个对象不一定相等。
  • @ThomasLevesque 你说得对,具有相同哈希码的两个对象不一定相等。但是GetHashCode() 仍然在Equals() 的很多实现中使用。这就是我所说的那个意思。 GetHashCode()Equals() 中经常被用作确定不等式 的快捷方式,因为如果两个对象具有不同 哈希码,它们必须是不相等的对象并且其余的相等检查不必执行。
  • @bitbonk 通常,GetHashCode()Equals() 都需要查看两个对象的所有字段(如果哈希码相等或未检查,Equals 必须这样做)。因此,在Equals() 内调用GetHashCode() 通常是多余的,并且可能会降低性能。 Equals() 也可以短路,使其更快 - 但是在某些情况下,哈希码可能会被缓存,从而使GetHashCode() 检查更快,因此值得。请参阅this question 了解更多信息。
  • 2020 年 1 月更新:Eric Lippert 的博客位于:docs.microsoft.com/en-us/archive/blogs/ericlippert/…

标签: .net algorithm hashcode gethashcode


【解决方案1】:

我通常采用类似于 Josh Bloch 的 fabulous Effective Java 中给出的实现。它速度很快,并且创建了一个不太可能导致冲突的非常好的哈希。选择两个不同的素数,例如17 和 23,然后做:

public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        // Suitable nullity checks etc, of course :)
        hash = hash * 23 + field1.GetHashCode();
        hash = hash * 23 + field2.GetHashCode();
        hash = hash * 23 + field3.GetHashCode();
        return hash;
    }
}

如 cmets 中所述,您可能会发现最好选择一个较大的素数进行相乘。显然 486187739 很好......虽然我看到的大多数小数字示例都倾向于使用素数,但至少有类似的算法经常使用非素数。例如,在后面的 not-quite-FNV 示例中,我使用了显然工作良好的数字 - 但初始值不是质数。 (不过,乘法常数 素数。我不知道这有多重要。)

这比XORing 哈希码的常见做法要好,主要有两个原因。假设我们有一个包含两个 int 字段的类型:

XorHash(x, x) == XorHash(y, y) == 0 for all x, y
XorHash(x, y) == XorHash(y, x) for all x, y

顺便说一句,早期的算法是 C# 编译器当前用于匿名类型的算法。

This page 提供了很多选项。我认为在大多数情况下,上述内容“足够好”,并且非常容易记住和正确。 FNV 替代方案同样简单,但使用不同的常量和XOR 而不是ADD 作为组合操作。它看起来有点类似于下面的代码,但正常的 FNV 算法对单个字节进行操作,因此这需要修改为每个字节执行一次迭代,而不是每个 32 位哈希值。 FNV 也是为可变长度的数据设计的,而我们在这里使用它的方式总是针对相同数量的字段值。对此答案的评论表明,这里的代码实际上并不像上面的添加方法那样有效(在测试的示例案例中)。

// Note: Not quite FNV!
public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = (int) 2166136261;
        // Suitable nullity checks etc, of course :)
        hash = (hash * 16777619) ^ field1.GetHashCode();
        hash = (hash * 16777619) ^ field2.GetHashCode();
        hash = (hash * 16777619) ^ field3.GetHashCode();
        return hash;
    }
}

请注意,需要注意的一件事是,理想情况下,您应该防止您的平等敏感(因此哈希码敏感)状态在将其添加到依赖于哈希码的集合后发生变化。

根据documentation

您可以为不可变引用类型覆盖 GetHashCode。一般来说,对于可变引用类型,只有在以下情况下才应该覆盖 GetHashCode:

  • 您可以从不可变的字段计算哈希码;或
  • 您可以确保当可变对象包含在依赖于其哈希码的集合中时,该对象的哈希码不会改变。

FNV 文章的链接已损坏,但此处是 Internet 档案中的副本:Eternally Confuzzled - The Art of Hashing

【讨论】:

  • 你提到的书中描述的算法实际上更详细一点,它特别描述了对不同数据类型的字段做什么。例如:对于 long 类型的字段,使用 (int)(field ^ f >>> 32) 而不是简单地调用 GetHashcode。 long.GetHashCodes 是这样实现的吗?
  • 是的,Int64.GetHashCode 正是这样做的。当然,在 Java 中,这需要装箱。这提醒了我 - 是时候添加本书的链接了......
  • 23 不是好的选择,因为(从 .net 3.5 SP1 开始)Dictionary<TKey,TValue> 假定以某些素数为模的良好分布。而23就是其中之一。因此,如果您有一个容量为 23 的字典,则只有对 GetHashCode 的最后贡献会影响复合哈希码。所以我宁愿使用 29 而不是 23。
  • @CodeInChaos:只有最后一个贡献会影响存储桶 - 所以在最坏的情况下,它可能必须查看字典中的 所有 23 个条目。它仍然会检查每个条目的实际哈希码,这会很便宜。如果你有一本那么小的字典,它就不太重要了。
  • @Vajda:我通常使用 0 作为null 的有效哈希码 - 这与忽略该字段不同。
【解决方案2】:

ValueTuple - C# 7 更新

正如@cactuaroid 在 cmets 中提到的,可以使用值元组。这节省了一些击键,更重要的是纯粹在堆栈上执行(无垃圾):

(PropA, PropB, PropC, PropD).GetHashCode();

(注意:使用匿名类型的原始技术似乎是在堆上创建一个对象,即垃圾,因为匿名类型是作为类实现的,尽管这可能会被编译器优化。对这些选项进行基准测试会很有趣,但元组选项应该更好。)

匿名类型(原始答案)

Microsoft 已经提供了一个很好的通用 HashCode 生成器:只需将您的属性/字段值复制到匿名类型并对其进行哈希处理:

new { PropA, PropB, PropC, PropD }.GetHashCode();

这适用于任意数量的属性。它不使用拳击。它只是使用已经在匿名类型框架中实现的算法。

【讨论】:

  • 是的,匿名 GetHashCode 实现非常有效(顺便说一句,它与 Jon Skeet 的答案中的相同),但此解决方案的唯一问题是您在任何 @ 处生成一个新实例987654325@电话。这可能有点开销,特别是在密集访问大型散列集合的情况下......
  • @digEmAll 好点,我没有考虑创建新对象的开销。 Jon Skeet 的答案是最有效的,不会使用拳击。 (@Kumba 要解决 VB 中未选中的问题,只需使用 Int64(长整数)并在计算后截断它。)
  • VB.NET 必须在匿名类型创建中使用 Key:New With {Key PropA}.GetHashCode() 否则 GetHashCode 不会为具有相同“标识”属性的不同对象返回相同的哈希码。
  • @Keith 在这种情况下,我会考虑将 IEnumerable 作为列表值保存在某处,而不是在每次计算哈希码时枚举它。在许多情况下,每次在 GetHashCode 中计算 ToList 都会损害性能。
  • 对于那些喜欢这个的人,(PropA, PropB, PropC, PropD).GetHashCode() 现在可以在 C#7 上使用,而无需担心 GC 压力@digEmAll。 Quick and Simple Hash Code Combinations
【解决方案3】:

这是我的哈希码助手。
它的优点是它使用泛型类型参数,因此不会导致装箱:

public static class HashHelper
{
    public static int GetHashCode<T1, T2>(T1 arg1, T2 arg2)
    {
         unchecked
         {
             return 31 * arg1.GetHashCode() + arg2.GetHashCode();
         }
    }

    public static int GetHashCode<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
    {
        unchecked
        {
            int hash = arg1.GetHashCode();
            hash = 31 * hash + arg2.GetHashCode();
            return 31 * hash + arg3.GetHashCode();
        }
    }

    public static int GetHashCode<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, 
        T4 arg4)
    {
        unchecked
        {
            int hash = arg1.GetHashCode();
            hash = 31 * hash + arg2.GetHashCode();
            hash = 31 * hash + arg3.GetHashCode();
            return 31 * hash + arg4.GetHashCode();
        }
    }

    public static int GetHashCode<T>(T[] list)
    {
        unchecked
        {
            int hash = 0;
            foreach (var item in list)
            {
                hash = 31 * hash + item.GetHashCode();
            }
            return hash;
        }
    }

    public static int GetHashCode<T>(IEnumerable<T> list)
    {
        unchecked
        {
            int hash = 0;
            foreach (var item in list)
            {
                hash = 31 * hash + item.GetHashCode();
            }
            return hash;
        }
    }

    /// <summary>
    /// Gets a hashcode for a collection for that the order of items 
    /// does not matter.
    /// So {1, 2, 3} and {3, 2, 1} will get same hash code.
    /// </summary>
    public static int GetHashCodeForOrderNoMatterCollection<T>(
        IEnumerable<T> list)
    {
        unchecked
        {
            int hash = 0;
            int count = 0;
            foreach (var item in list)
            {
                hash += item.GetHashCode();
                count++;
            }
            return 31 * hash + count.GetHashCode();
        }
    }

    /// <summary>
    /// Alternative way to get a hashcode is to use a fluent 
    /// interface like this:<br />
    /// return 0.CombineHashCode(field1).CombineHashCode(field2).
    ///     CombineHashCode(field3);
    /// </summary>
    public static int CombineHashCode<T>(this int hashCode, T arg)
    {
        unchecked
        {
            return 31 * hashCode + arg.GetHashCode();   
        }
    }

它还有扩展方法来提供流畅的界面,所以你可以这样使用它:

public override int GetHashCode()
{
    return HashHelper.GetHashCode(Manufacturer, PartN, Quantity);
}

或者像这样:

public override int GetHashCode()
{
    return 0.CombineHashCode(Manufacturer)
        .CombineHashCode(PartN)
        .CombineHashCode(Quantity);
}

【讨论】:

  • 不需要T[],因为它已经是IEnumerable&lt;T&gt;
  • 您可以重构这些方法并将核心逻辑限制为一个函数
  • 顺便说一句,31 是 CPU 上的移位和减法,速度非常快。
  • @nightcoder 你可以使用params
  • @ChuiTey 这是所有Mersenne Primes 的共同点。
【解决方案4】:

使用System.HashCode

如果您使用的是 .NET Standard 2.1 或更高版本,则可以使用 System.HashCode 结构。在早期的框架中,它可以从Microsoft.Bcl.HashCode 包中获得。有两种使用方法:

HashCode.Combine

Combine 方法可用于创建一个哈希码,最多给定八个对象。

public override int GetHashCode() => HashCode.Combine(this.object1, this.object2);

HashCode.Add

Add 方法帮助您处理集合:

public override int GetHashCode()
{
    var hashCode = new HashCode();
    hashCode.Add(this.object1);
    foreach (var item in this.collection)
    {
        hashCode.Add(item);
    }
    return hashCode.ToHashCode();
}

GetHashCode 变得简单

System.HashCode 的替代品,超级易于使用,同时速度仍然很快。您可以阅读完整的博文“GetHashCode Made Easy”了解更多详细信息和 cmets。

使用示例

public class SuperHero
{
    public int Age { get; set; }
    public string Name { get; set; }
    public List<string> Powers { get; set; }

    public override int GetHashCode() =>
        HashCode.Of(this.Name).And(this.Age).AndEach(this.Powers);
}

实施

public struct HashCode : IEquatable<HashCode>
{
    private const int EmptyCollectionPrimeNumber = 19;
    private readonly int value;

    private HashCode(int value) => this.value = value;

    public static implicit operator int(HashCode hashCode) => hashCode.value;

    public static bool operator ==(HashCode left, HashCode right) => left.Equals(right);

    public static bool operator !=(HashCode left, HashCode right) => !(left == right);

    public static HashCode Of<T>(T item) => new HashCode(GetHashCode(item));

    public static HashCode OfEach<T>(IEnumerable<T> items) =>
        items == null ? new HashCode(0) : new HashCode(GetHashCode(items, 0));

    public HashCode And<T>(T item) => 
        new HashCode(CombineHashCodes(this.value, GetHashCode(item)));

    public HashCode AndEach<T>(IEnumerable<T> items)
    {
        if (items == null)
        {
            return new HashCode(this.value);
        }

        return new HashCode(GetHashCode(items, this.value));
    }

    public bool Equals(HashCode other) => this.value.Equals(other.value);

    public override bool Equals(object obj)
    {
        if (obj is HashCode)
        {
            return this.Equals((HashCode)obj);
        }

        return false;
    }

    public override int GetHashCode() => this.value.GetHashCode();

    private static int CombineHashCodes(int h1, int h2)
    {
        unchecked
        {
            // Code copied from System.Tuple a good way to combine hashes.
            return ((h1 << 5) + h1) ^ h2;
        }
    }

    private static int GetHashCode<T>(T item) => item?.GetHashCode() ?? 0;

    private static int GetHashCode<T>(IEnumerable<T> items, int startHashCode)
    {
        var temp = startHashCode;

        var enumerator = items.GetEnumerator();
        if (enumerator.MoveNext())
        {
            temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));

            while (enumerator.MoveNext())
            {
                temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));
            }
        }
        else
        {
            temp = CombineHashCodes(temp, EmptyCollectionPrimeNumber);
        }

        return temp;
    }
}

什么是好的算法?

性能

计算哈希码的算法需要很快。一个简单的算法通常会更快。不分配额外内存的方法也将减少垃圾收集的需求,这反过来也将提高性能。

特别是在 C# 哈希函数中,您经常使用 unchecked 关键字来停止溢出检查以提高性能。

确定性

哈希算法必须是deterministic,即给定相同的输入,它必须始终产生相同的输出。

减少碰撞

计算哈希码的算法需要将hash collisions 保持在最小值。哈希冲突是当对两个不同对象的两次调用GetHashCode 产生相同的哈希码时发生的情况。请注意,允许发生碰撞(有些人误解为不允许发生碰撞),但应将其保持在最低限度。

很多哈希函数都包含像1723 这样的幻数。这些是特殊的prime numbers,与使用非素数相比,它们的数学特性有助于减少哈希冲突。

哈希均匀度

一个好的散列函数应该在其输出范围内尽可能均匀地映射预期输入,即它应该基于均匀分布的输入输出广泛的散列。它应该具有哈希一致性。

防止 DoS

在 .NET Core 中,每次重新启动应用程序都会获得不同的哈希码。这是一项防止拒绝服务攻击 (DoS) 的安全功能。对于 .NET Framework,您应该通过添加以下 App.config 文件来启用此功能:

<?xml version ="1.0"?>  
<configuration>  
   <runtime>  
      <UseRandomizedStringHashAlgorithm enabled="1" />  
   </runtime>  
</configuration>

由于此功能,哈希码不应在创建它们的应用程序域之外使用,它们不应用作集合中的关键字段,也不应被持久化。

阅读更多关于here的信息。

加密安全?

算法不必是Cryptographic hash function。这意味着它不必满足以下条件:

  • 生成产生给定哈希值的消息是不可行的。
  • 不可能找到两条具有相同哈希值的不同消息。
  • 对消息的微小更改应该会大幅更改哈希值,以致新哈希值看起来与旧哈希值不相关(雪崩效应)。

【讨论】:

  • 这是一个很好的答案。另外,您可以考虑将“速度”更改为“性能”并添加免分配属性。内置的HashCode 类型也可以满足这一点。
  • 这与上面@ricklove 最近更新的ValueTuple.GetHashCode() 答案相比如何?
  • HashCode.Combine 是一个静态方法,不会分配任何东西,而ValueTuple 将开始在堆栈上分配。
  • HashCode.Of(this.Name).And(this.Age).AndEach(this.Powers) - 这是很好的语法:)
  • they should never be used as key fields in a collection,这不就是哈希码的重点吗?以及哈希表、哈希集、字典的存在?
【解决方案5】:

我在 Helper 库中有一个 Hashing 类,我将其用于此目的。

/// <summary> 
/// This is a simple hashing function from Robert Sedgwicks Hashing in C book.
/// Also, some simple optimizations to the algorithm in order to speed up
/// its hashing process have been added. from: www.partow.net
/// </summary>
/// <param name="input">array of objects, parameters combination that you need
/// to get a unique hash code for them</param>
/// <returns>Hash code</returns>
public static int RSHash(params object[] input)
{
    const int b = 378551;
    int a = 63689;
    int hash = 0;

    // If it overflows then just wrap around
    unchecked
    {
        for (int i = 0; i < input.Length; i++)
        {
            if (input[i] != null)
            {
                hash = hash * a + input[i].GetHashCode();
                a = a * b;
            }
        }
    }

    return hash;
}

那么,你可以简单地把它当作:

public override int GetHashCode()
{
    return Hashing.RSHash(_field1, _field2, _field3);
}

我没有评估它的性能,所以欢迎任何反馈。

【讨论】:

  • 好吧,如果字段是值类型,它会导致装箱。
  • "以后可以通过捕获溢出异常来增强" unchecked 的全部意义在于避免溢出异常,这在 GetHashCode 上是需要的。所以如果值溢出int也不是错误的,而且完全没有伤害。
  • 这个算法的一个问题是任何充满空值的数组总是返回 0,不管它的长度是多少
  • 这个辅助方法也分配了一个新对象[]
  • 正如@NathanAdams 所提到的,完全跳过null 的事实可能会给您带来意想不到的结果。当input[i] 为空时,您应该只使用一些常量值而不是input[i].GetHashCode(),而不是跳过它们。
【解决方案6】:

这是我使用 Jon Skeet's implementation 的助手类。

public static class HashCode
{
    public const int Start = 17;

    public static int Hash<T>(this int hash, T obj)
    {
        var h = EqualityComparer<T>.Default.GetHashCode(obj);
        return unchecked((hash * 31) + h);
    }
}

用法:

public override int GetHashCode()
{
    return HashCode.Start
        .Hash(_field1)
        .Hash(_field2)
        .Hash(_field3);
}

如果您想避免为 System.Int32 编写扩展方法:

public readonly struct HashCode
{
    private readonly int _value;

    public HashCode(int value) => _value = value;

    public static HashCode Start { get; } = new HashCode(17);

    public static implicit operator int(HashCode hash) => hash._value;

    public HashCode Hash<T>(T obj)
    {
        var h = EqualityComparer<T>.Default.GetHashCode(obj);
        return unchecked(new HashCode((_value * 31) + h));
    }

    public override int GetHashCode() => _value;
}

它仍然避免了任何堆分配,并且使用方式完全相同:

public override int GetHashCode()
{
    // This time `HashCode.Start` is not an `Int32`, it's a `HashCode` instance.
    // And the result is implicitly converted to `Int32`.
    return HashCode.Start
        .Hash(_field1)
        .Hash(_field2)     
        .Hash(_field3);
}

编辑(2018 年 5 月):EqualityComparer&lt;T&gt;.Default getter 现在是 JIT 内在函数 - Stephen Toub 在this blog post 中提到了pull request

【讨论】:

  • 我会将带有三级运算符的行更改为:var h = Equals(obj, default(T)) ? 0 : obj.GetHashCode();
  • 我相信带有obj != null 的三元运算符将编译为box 指令,如果T 是值类型,它将分配内存。相反,您可以使用obj.Equals(null),它将编译为Equals 方法的虚拟调用。
  • 因为this.hashCode != h。它不会返回相同的值。
  • 对不起,设法删除我的评论而不是编辑它。创建一个新结构然后将 hashCode 更改为非只读并执行以下操作是否更有益:“unchecked { this.hashCode ^= h * 397; } return this;”例如?
  • 不变性有它的好处 (Why are mutable structs evil?)。关于性能,我所做的非常便宜,因为它不会在堆中分配任何空间。
【解决方案7】:

在大多数情况下,当 Equals() 比较多个字段时,您的 GetHash() 是否在一个字段或多个字段上散列并不重要。您只需要确保计算哈希值真的很便宜(请不要分配)和快速(没有繁重的计算,当然也没有数据库连接)并提供良好的分布.

繁重的工作应该是 Equals() 方法的一部分;散列应该是一个非常便宜的操作,以便在尽可能少的项目上调用 Equals()。

最后一个提示:不要依赖 GetHashCode() 在多个应用程序运行中保持稳定。许多 .Net 类型不保证其哈希码在重启后保持不变,因此您应该只将 GetHashCode() 的值用于内存数据结构。

【讨论】:

  • “在大多数情况下,当 Equals() 比较多个字段时,您的 GetHash() 是否在一个字段或多个字段上散列并不重要。”这是一个危险的建议,因为对于仅在未散列字段中不同的对象,您将遇到散列冲突。如果这种情况频繁发生,基于散列的集合(HashMap、HashSet 等)的性能将会下降(最坏的情况下可达 O(n))。
  • 这实际上发生在 Java 中:在 JDK 的早期版本中,String.hashCode() 只考虑字符串的开头;如果您在 HashMaps 中使用字符串作为键,这会导致性能问题,而 HashMaps 仅在末尾有所不同(这很常见,例如对于 URL)。因此算法发生了变化(我相信在 JDK 1.2 或 1.3 中)。
  • 如果那个字段“提供了良好的分布”(我回答的最后一部分),那么一个字段就足够了。如果它没有提供良好的分布,然后(就在那时)你需要另一个计算。 (例如,只使用另一个确实提供良好分布的字段,或使用多个字段)
  • 我不认为让GetHashCode 执行内存分配有问题,前提是它只在第一次使用时这样做(随后的调用只是返回一个缓存结果)。重要的不是人们应该竭尽全力避免碰撞,而是应该避免“系统性”碰撞。如果一个类型有两个int 字段oldXnewX,它们经常相差一个,那么oldX^newX 的哈希值将分配90% 的此类记录哈希值1、2、4 或8。使用@ 987654326@ [未经检查的算术] 可能会产生更多的冲突...
  • ...比更复杂的函数,但是如果每个哈希值有两个相关联的东西,那么具有 500,000 个不同哈希值的 1,000,000 个事物的集合将非常好,如果一个哈希值有 500,001 个则非常糟糕事物和其他事物各有一个。
【解决方案8】:

直到最近,我的回答与 Jon Skeet 的回答非常接近。然而,我最近开始了一个使用二次幂哈希表的项目,即内部表大小为 8、16、32 等的哈希表。有一个很好的理由支持质数大小,但是有二次方大小也有一些优势。

而且它非常糟糕。因此,经过一些实验和研究后,我开始使用以下内容重新散列我的哈希:

public static int ReHash(int source)
{
  unchecked
  {
    ulong c = 0xDEADBEEFDEADBEEF + (ulong)source;
    ulong d = 0xE2ADBEEFDEADBEEF ^ c;
    ulong a = d += c = c << 15 | c >> -15;
    ulong b = a += d = d << 52 | d >> -52;
    c ^= b += a = a << 26 | a >> -26;
    d ^= c += b = b << 51 | b >> -51;
    a ^= d += c = c << 28 | c >> -28;
    b ^= a += d = d << 9 | d >> -9;
    c ^= b += a = a << 47 | a >> -47;
    d ^= c += b << 54 | b >> -54;
    a ^= d += c << 32 | c >> 32;
    a += d << 25 | d >> -25;
    return (int)(a >> 1);
  }
}

然后我的二次幂哈希表不再糟糕了。

这让我感到不安,因为上述内容不应该工作。或者更准确地说,除非最初的 GetHashCode() 以非常特殊的方式很差,否则它不应该工作。

重新混合一个哈希码并不能改进一个很好的哈希码,因为唯一可能的效果是我们引入了更多的冲突。

重新混合哈希码并不能改善糟糕的哈希码,因为唯一可能的效果是我们改变了例如值 53 上的大量碰撞到大量值 18,3487,291。

重新混合散列码只能改进散列码,该散列码在避免其范围内的绝对冲突(232 个可能值)方面至少做得相当好,但在取模时在避免冲突方面表现不佳在哈希表中实际使用。虽然 2 的幂表的更简单的模数使这一点更加明显,但它也对更常见的素数表产生了负面影响,这并不那么明显(重新散列的额外工作将超过好处,但好处仍然存在)。

编辑:我也在使用开放寻址,这也会增加对碰撞的敏感度,也许比它是二次方的事实更重要。

好吧,令人不安的是,.NET(或研究here)中的string.GetHashCode() 实现可以通过这种方式改进多少(由于更少的碰撞,测试运行速度提高了大约 20-30 倍)更令人不安的是我自己的哈希码可以改进多少(远不止这些)。

我过去编写的所有 GetHashCode() 实现,并且确实用作此站点上的答案的基础,都比我所经历的要糟糕得多。很多时候它对于很多用途来说都“足够好”,但我想要更好的东西。

所以我把那个项目放在一边(无论如何它是一个宠物项目),并开始研究如何在 .NET 中快速生成一个好的、分布良好的哈希码。

最后我决定将SpookyHash 移植到.NET。实际上,上面的代码是使用 SpookyHash 从 32 位输入生成 32 位输出的快速路径版本。

现在,SpookyHash 不是一个快速记住代码的好方法。我的端口更是如此,因为我手动内联了很多以提高速度*。但这就是代码重用的目的。

然后我把那个项目放在一边,因为就像原来的项目产生了如何产生更好的哈希码的问题一样,这个项目产生了如何产生更好的哈希码的问题.NET 内存。

然后我回来了,并产生了很多重载,以便轻松地将几乎所有本机类型(decimal† 除外)提供给哈希码。

它很快,Bob Jenkins 应该得到大部分的赞誉,因为我从他移植的原始代码仍然更快,尤其是在算法优化的 64 位机器上‡。

完整的代码可以在https://bitbucket.org/JonHanna/spookilysharp/src看到,但请考虑上面的代码是它的简化版本。

但是,由于它现在已经编写好了,因此可以更轻松地使用它:

public override int GetHashCode()
{
  var hash = new SpookyHash();
  hash.Update(field1);
  hash.Update(field2);
  hash.Update(field3);
  return hash.Final().GetHashCode();
}

它还需要种子值,因此如果您需要处理不受信任的输入并希望防止 Hash DoS 攻击,您可以根据正常运行时间或类似设置设置种子,并使攻击者无法预测结果:

private static long hashSeed0 = Environment.TickCount;
private static long hashSeed1 = DateTime.Now.Ticks;
public override int GetHashCode()
{
  //produce different hashes ever time this application is restarted
  //but remain consistent in each run, so attackers have a harder time
  //DoSing the hash tables.
  var hash = new SpookyHash(hashSeed0, hashSeed1);
  hash.Update(field1);
  hash.Update(field2);
  hash.Update(field3);
  return hash.Final().GetHashCode();
}

*其中一个很大的惊喜是手动内联返回(x &lt;&lt; n) | (x &gt;&gt; -n) 的旋转方法改进了一些事情。我本来可以肯定抖动会为我内联,但分析显示并非如此。

decimal 从 .NET 的角度来看并不是原生的,尽管它来自 C#。它的问题在于它自己的GetHashCode() 将精度视为重要,而它自己的Equals() 则没有。两者都是有效的选择,但不能像那样混合。在实现自己的版本时,您需要选择做一个或另一个,但我不知道您想要哪个。

‡通过比较。如果在字符串上使用,64 位上的 SpookyHash 比 32 位上的 string.GetHashCode() 快得多,这比 64 位上的 string.GetHashCode() 稍快,这比 32 位上的 SpookyHash 快得多,尽管仍然足够快合理的选择。

【讨论】:

  • 当将多个哈希值合并为一个时,我倾向于使用long 值作为中间结果,然后将最终结果降低到int。这似乎是个好主意?我担心的是一个人使用例如hash=(hash*31)+nextField,那么成对的匹配值只会影响hash的高27位。让计算扩展到 long 并将内容包装进去可以最大限度地减少这种危险。
  • @supercat 这取决于你最终的 munging 分布。 SpookilySharp 库将确保分布良好,理想情况下(因为它不需要创建对象)通过传递指向 blittable 类型的指针,或传递它直接处理的枚举之一,但如果您还没有 blittable数据或合适的枚举,然后按照上面的答案使用多个值调用.Update() 就可以了。
  • @JonHanna 您愿意更准确地了解您遇到的问题行为吗?我正在尝试实现一个库,使实现值对象变得微不足道 (ValueUtils),我希望有一个测试集在二次幂哈希表中展示较差的哈希混溶性。
  • @EamonNerbonne 我真的没有什么比“整体时间更慢”更精确的了。正如我在编辑中添加的那样,我使用开放寻址这一事实可能比二次幂因素更重要。我确实计划在一个特定项目上做一些测试用例,在那里我将比较几种不同的方法,所以在那之后我可能会给你一个更好的答案,尽管这不是一个高优先级(一个没有紧迫需求的个人项目,所以当我得到它时,我会得到它......)
  • @JonHanna:是的,我知道个人项目的进度如何——祝你好运!无论如何,我发现我没有很好地表达最后一条评论:我的意思是询问有问题的输入,而不一定是导致问题的详细信息。我很乐意将其用作测试集(或测试集的灵感)。无论如何 - 祝你的宠物项目好运:-)。
【解决方案9】:

截至https://github.com/dotnet/coreclr/pull/14863,有一种生成哈希码的新方法非常简单!随便写

public override int GetHashCode()
    => HashCode.Combine(field1, field2, field3);

这将生成高质量的哈希码,您不必担心实现细节。

【讨论】:

  • 这看起来像是一个很好的补充......有什么办法知道将在哪个版本的 .NET Core 中发布?
  • @DanJ 多么令人高兴的巧合,corefx 的 HashCode 更改在您发表评论前几个小时就被合并了 :) 该类型计划在 .NET Core 2.1 中发布。
  • 这太棒了——而且周转时间也很长。赞成。 :)
  • @DanJ 更好的消息——它现在应该可以在 dotnet-core MyGet 提要上托管的 CoreFX 的夜间版本中使用。
  • 甜蜜 - 这对我的工作没有帮助,因为我们不是很那个前沿,但很高兴知道。干杯!
【解决方案10】:

这个不错:

/// <summary>
/// Helper class for generating hash codes suitable 
/// for use in hashing algorithms and data structures like a hash table. 
/// </summary>
public static class HashCodeHelper
{
    private static int GetHashCodeInternal(int key1, int key2)
    {
        unchecked
        {
           var num = 0x7e53a269;
           num = (-1521134295 * num) + key1;
           num += (num << 10);
           num ^= (num >> 6);

           num = ((-1521134295 * num) + key2);
           num += (num << 10);
           num ^= (num >> 6);

           return num;
        }
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="arr">An array of objects used for generating the 
    /// hash code.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data 
    /// structures like a hash table. 
    /// </returns>
    public static int GetHashCode(params object[] arr)
    {
        int hash = 0;
        foreach (var item in arr)
            hash = GetHashCodeInternal(hash, item.GetHashCode());
        return hash;
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <param name="obj3">The third object.</param>
    /// <param name="obj4">The fourth object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and
    /// data structures like a hash table.
    /// </returns>
    public static int GetHashCode<T1, T2, T3, T4>(T1 obj1, T2 obj2, T3 obj3,
        T4 obj4)
    {
        return GetHashCode(obj1, GetHashCode(obj2, obj3, obj4));
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <param name="obj3">The third object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data 
    /// structures like a hash table. 
    /// </returns>
    public static int GetHashCode<T1, T2, T3>(T1 obj1, T2 obj2, T3 obj3)
    {
        return GetHashCode(obj1, GetHashCode(obj2, obj3));
    }

    /// <summary>
    /// Returns a hash code for the specified objects
    /// </summary>
    /// <param name="obj1">The first object.</param>
    /// <param name="obj2">The second object.</param>
    /// <returns>
    /// A hash code, suitable for use in hashing algorithms and data 
    /// structures like a hash table. 
    /// </returns>
    public static int GetHashCode<T1, T2>(T1 obj1, T2 obj2)
    {
        return GetHashCodeInternal(obj1.GetHashCode(), obj2.GetHashCode());
    }
}

下面是如何使用它:

private struct Key
{
    private Type _type;
    private string _field;

    public Type Type { get { return _type; } }
    public string Field { get { return _field; } }

    public Key(Type type, string field)
    {
        _type = type;
        _field = field;
    }

    public override int GetHashCode()
    {
        return HashCodeHelper.GetHashCode(_field, _type);
    }

    public override bool Equals(object obj)
    {
        if (!(obj is Key))
            return false;
        var tf = (Key)obj;
        return tf._field.Equals(_field) && tf._type.Equals(_type);
    }
}

【讨论】:

  • 密钥是如何确定的? GetHashCode() 不带任何参数,因此它需要使用两个需要以某种方式确定的 Key 来调用它。抱歉,没有进一步的解释,这只看起来很聪明,但不是那么好。
  • 为什么需要泛型重载?类型并不重要(并且未在您的代码中使用),因为 所有 对象都有一个 GetHashCode() 方法,因此您始终可以将该方法与 params 数组参数一起使用。还是我在这里遗漏了什么?
  • 当你使用对象而不是泛型时,你会得到装箱和内存分配,这在 GetHashCode 中是不想要的。所以泛型是要走的路。
  • 后面的 shift/xor 步骤(h += (h &lt;&lt; 10); h ^= (h &gt;&gt; 6); h += (h &lt;&lt; 3); h ^= (h &gt;&gt; 11); h += (h &lt;&lt; 15); 有一个代码异味:它们不依赖于任何输入,对我来说看起来非常多余。
  • @Magnus 是的,我会删除我原来的评论。请注意,这可能不如这里的其他一些解决方案那么快,但正如你所说的那样不重要。分布很棒,比这里的大多数解决方案都要好,所以我+1! :)
【解决方案11】:

这是the algorithm posted above by Jon Skeet 的另一个流畅实现,但不包括分配或装箱操作:

public static class Hash
{
    public const int Base = 17;

    public static int HashObject(this int hash, object obj)
    {
        unchecked { return hash * 23 + (obj == null ? 0 : obj.GetHashCode()); }
    }

    public static int HashValue<T>(this int hash, T value)
        where T : struct
    {
        unchecked { return hash * 23 + value.GetHashCode(); }
    }
}

用法:

public class MyType<T>
{
    public string Name { get; set; }

    public string Description { get; set; }

    public int Value { get; set; }

    public IEnumerable<T> Children { get; set; }

    public override int GetHashCode()
    {
        return Hash.Base
            .HashObject(this.Name)
            .HashObject(this.Description)
            .HashValue(this.Value)
            .HashObject(this.Children);
    }
}

由于泛型类型约束,编译器将确保HashValue 不会被类调用。但是没有编译器支持HashObject,因为添加泛型参数也会添加装箱操作。

【讨论】:

    【解决方案12】:

    这是我的简单方法。我为此使用了经典的构建器模式。它是类型安全的(无装箱/拆箱),并且与 .NET 2.0 兼容(无扩展方法等)。

    它是这样使用的:

    public override int GetHashCode()
    {
        HashBuilder b = new HashBuilder();
        b.AddItems(this.member1, this.member2, this.member3);
        return b.Result;
    } 
    

    这里是实际的构建器类:

    internal class HashBuilder
    {
        private const int Prime1 = 17;
        private const int Prime2 = 23;
        private int result = Prime1;
    
        public HashBuilder()
        {
        }
    
        public HashBuilder(int startHash)
        {
            this.result = startHash;
        }
    
        public int Result
        {
            get
            {
                return this.result;
            }
        }
    
        public void AddItem<T>(T item)
        {
            unchecked
            {
                this.result = this.result * Prime2 + item.GetHashCode();
            }
        }
    
        public void AddItems<T1, T2>(T1 item1, T2 item2)
        {
            this.AddItem(item1);
            this.AddItem(item2);
        }
    
        public void AddItems<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
        {
            this.AddItem(item1);
            this.AddItem(item2);
            this.AddItem(item3);
        }
    
        public void AddItems<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, 
            T4 item4)
        {
            this.AddItem(item1);
            this.AddItem(item2);
            this.AddItem(item3);
            this.AddItem(item4);
        }
    
        public void AddItems<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, 
            T4 item4, T5 item5)
        {
            this.AddItem(item1);
            this.AddItem(item2);
            this.AddItem(item3);
            this.AddItem(item4);
            this.AddItem(item5);
        }        
    
        public void AddItems<T>(params T[] items)
        {
            foreach (T item in items)
            {
                this.AddItem(item);
            }
        }
    }
    

    【讨论】:

    • 您可以避免在 gethashcode 函数中创建对象,如 Mangus 的回答。只需调用该死的静态哈希函数(谁关心启动哈希)。此外,您可以在帮助程序类中更频繁地使用AddItems&lt;T&gt;(params T[] items) 方法(而不是每次调用AddItem(T))。
    • 当你经常使用this.result * Prime2 * item.GetHashCode()时,你发现this.result * Prime2 + item.GetHashCode()有什么好处?
    • 我不能更频繁地使用AddItems&lt;T&gt;(params T[] items),因为typeof(T1) != typeof(T2) 等等。
    【解决方案13】:

    如果我们的属性不超过 8 个(希望如此),这是另一种选择。

    ValueTuple 是一个结构,似乎有一个可靠的GetHashCode 实现。

    这意味着我们可以简单地这样做:

    // Yay, no allocations and no custom implementations!
    public override int GetHashCode() => (this.PropA, this.PropB).GetHashCode();
    

    让我们看看 .NET Core 当前对ValueTupleGetHashCode 的实现。

    这是来自ValueTuple

        internal static int CombineHashCodes(int h1, int h2)
        {
            return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);
        }
    
        internal static int CombineHashCodes(int h1, int h2, int h3)
        {
            return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);
        }
    

    这是来自HashHelper

        public static readonly int RandomSeed = Guid.NewGuid().GetHashCode();
    
        public static int Combine(int h1, int h2)
        {
            unchecked
            {
                // RyuJIT optimizes this to use the ROL instruction
                // Related GitHub pull request: dotnet/coreclr#1830
                uint rol5 = ((uint)h1 << 5) | ((uint)h1 >> 27);
                return ((int)rol5 + h1) ^ h2;
            }
        }
    

    英文:

    • 向左旋转(循环移位)h1 5 个位置。
    • 将结果和 h1 相加。
    • 将结果与 h2 进行异或。
    • 首先对 { static random seed, h1 } 执行上述操作。
    • 对于每个进一步的项目,对上一个结果和下一个项目(例如 h2)执行操作。

    如果能更多地了解这个 ROL-5 哈希码算法的属性,那就太好了。

    很遗憾,我们自己的GetHashCode 推迟到ValueTuple 可能没有我们希望和期望的那么快。相关讨论中的This comment 说明直接调用HashHelpers.Combine 的性能更高。另一方面,那个是内部的,所以我们必须复制代码,牺牲我们在这里获得的大部分内容。此外,我们将负责记住首先使用随机种子Combine。如果我们跳过这一步,我不知道会有什么后果。

    【讨论】:

    • 假设h1 &gt;&gt; 27为0忽略它,h1 &lt;&lt; 5等于h1 * 32因此它与h1 * 33 ^ h2相同。根据this page,它被称为“修改后的伯恩斯坦”。
    【解决方案14】:

    ReSharper 用户可以使用ReSharper -&gt; Edit -&gt; Generate Code -&gt; Equality Members 生成 GetHashCode、Equals 等。

    // ReSharper's GetHashCode looks like this
    public override int GetHashCode() {
        unchecked {
            int hashCode = Id;
            hashCode = (hashCode * 397) ^ IntMember;
            hashCode = (hashCode * 397) ^ OtherIntMember;
            hashCode = (hashCode * 397) ^ (RefMember != null ? RefMember.GetHashCode() : 0);
            // ...
            return hashCode;
        }
    }
    

    【讨论】:

      【解决方案15】:

      我的大部分工作都是通过数据库连接完成的,这意味着我的类都具有来自数据库的唯一标识符。我总是使用数据库中的 ID 来生成哈希码。

      // Unique ID from database
      private int _id;
      
      ...    
      {
        return _id.GetHashCode();
      }
      

      【讨论】:

      • 这意味着如果你有对象 Person 和 Account 并且它们都有并且 ID = 1,它们将具有相同的哈希码。这是不行的。
      • 其实上面的评论是不正确的。总是存在哈希码冲突的可能性(哈希码只定位桶,而不是单个对象)。所以这样的实现——对于包含混合对象的哈希码——会导致很多冲突,这是不可取的,但如果你的哈希表中只有单一类型的对象,那绝对没问题。它也不会均匀分布,但是 system.object 上的基本实现也没有,所以我不会太担心它......
      • 哈希码只能是 id,因为 id 是一个整数。不需要对整数调用 GetHashCode(它是一个恒等函数)
      • @DarrelLee 但他的 _id 可能是 Guid。使用_id.GetHashCode 是一种很好的编码习惯,因为意图很明确。
      • @1224 取决于使用模式,由于您给出的原因,它可能很糟糕,但它也可能很棒;如果你有一个没有漏洞的数字序列,那么你就有一个完美的散列,比任何算法都能产生的效果更好。如果您知道是这种情况,您甚至可以指望它并跳过相等性检查。
      【解决方案16】:

      与 nightcoder 的解决方案非常相似,只是如果你想提高质数会更容易。

      PS:这是你在嘴里吐一点的时候之一,知道这可以重构为一种具有 9 个默认值的方法,但它会更慢,所以你只需闭上眼睛,试着忘记它.

      /// <summary>
      /// Try not to look at the source code. It works. Just rely on it.
      /// </summary>
      public static class HashHelper
      {
          private const int PrimeOne = 17;
          private const int PrimeTwo = 23;
      
          public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10)
          {
              unchecked
              {
                  int hash = PrimeOne;
                  hash = hash * PrimeTwo + arg1.GetHashCode();
                  hash = hash * PrimeTwo + arg2.GetHashCode();
                  hash = hash * PrimeTwo + arg3.GetHashCode();
                  hash = hash * PrimeTwo + arg4.GetHashCode();
                  hash = hash * PrimeTwo + arg5.GetHashCode();
                  hash = hash * PrimeTwo + arg6.GetHashCode();
                  hash = hash * PrimeTwo + arg7.GetHashCode();
                  hash = hash * PrimeTwo + arg8.GetHashCode();
                  hash = hash * PrimeTwo + arg9.GetHashCode();
                  hash = hash * PrimeTwo + arg10.GetHashCode();
      
                  return hash;
              }
          }
      
          public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9)
          {
              unchecked
              {
                  int hash = PrimeOne;
                  hash = hash * PrimeTwo + arg1.GetHashCode();
                  hash = hash * PrimeTwo + arg2.GetHashCode();
                  hash = hash * PrimeTwo + arg3.GetHashCode();
                  hash = hash * PrimeTwo + arg4.GetHashCode();
                  hash = hash * PrimeTwo + arg5.GetHashCode();
                  hash = hash * PrimeTwo + arg6.GetHashCode();
                  hash = hash * PrimeTwo + arg7.GetHashCode();
                  hash = hash * PrimeTwo + arg8.GetHashCode();
                  hash = hash * PrimeTwo + arg9.GetHashCode();
      
                  return hash;
              }
          }
      
          public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8)
          {
              unchecked
              {
                  int hash = PrimeOne;
                  hash = hash * PrimeTwo + arg1.GetHashCode();
                  hash = hash * PrimeTwo + arg2.GetHashCode();
                  hash = hash * PrimeTwo + arg3.GetHashCode();
                  hash = hash * PrimeTwo + arg4.GetHashCode();
                  hash = hash * PrimeTwo + arg5.GetHashCode();
                  hash = hash * PrimeTwo + arg6.GetHashCode();
                  hash = hash * PrimeTwo + arg7.GetHashCode();
                  hash = hash * PrimeTwo + arg8.GetHashCode();
      
                  return hash;
              }
          }
      
          public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7)
          {
              unchecked
              {
                  int hash = PrimeOne;
                  hash = hash * PrimeTwo + arg1.GetHashCode();
                  hash = hash * PrimeTwo + arg2.GetHashCode();
                  hash = hash * PrimeTwo + arg3.GetHashCode();
                  hash = hash * PrimeTwo + arg4.GetHashCode();
                  hash = hash * PrimeTwo + arg5.GetHashCode();
                  hash = hash * PrimeTwo + arg6.GetHashCode();
                  hash = hash * PrimeTwo + arg7.GetHashCode();
      
                  return hash;
              }
          }
      
          public static int GetHashCode<T1, T2, T3, T4, T5, T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
          {
              unchecked
              {
                  int hash = PrimeOne;
                  hash = hash * PrimeTwo + arg1.GetHashCode();
                  hash = hash * PrimeTwo + arg2.GetHashCode();
                  hash = hash * PrimeTwo + arg3.GetHashCode();
                  hash = hash * PrimeTwo + arg4.GetHashCode();
                  hash = hash * PrimeTwo + arg5.GetHashCode();
                  hash = hash * PrimeTwo + arg6.GetHashCode();
      
                  return hash;
              }
          }
      
          public static int GetHashCode<T1, T2, T3, T4, T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
          {
              unchecked
              {
                  int hash = PrimeOne;
                  hash = hash * PrimeTwo + arg1.GetHashCode();
                  hash = hash * PrimeTwo + arg2.GetHashCode();
                  hash = hash * PrimeTwo + arg3.GetHashCode();
                  hash = hash * PrimeTwo + arg4.GetHashCode();
                  hash = hash * PrimeTwo + arg5.GetHashCode();
      
                  return hash;
              }
          }
      
          public static int GetHashCode<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)
          {
              unchecked
              {
                  int hash = PrimeOne;
                  hash = hash * PrimeTwo + arg1.GetHashCode();
                  hash = hash * PrimeTwo + arg2.GetHashCode();
                  hash = hash * PrimeTwo + arg3.GetHashCode();
                  hash = hash * PrimeTwo + arg4.GetHashCode();
      
                  return hash;
              }
          }
      
          public static int GetHashCode<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
          {
              unchecked
              {
                  int hash = PrimeOne;
                  hash = hash * PrimeTwo + arg1.GetHashCode();
                  hash = hash * PrimeTwo + arg2.GetHashCode();
                  hash = hash * PrimeTwo + arg3.GetHashCode();
      
                  return hash;
              }
          }
      
          public static int GetHashCode<T1, T2>(T1 arg1, T2 arg2)
          {
              unchecked
              {
                  int hash = PrimeOne;
                  hash = hash * PrimeTwo + arg1.GetHashCode();
                  hash = hash * PrimeTwo + arg2.GetHashCode();
      
                  return hash;
              }
          }
      }
      

      【讨论】:

      • 不处理空值。
      【解决方案17】:

      Microsoft 在几种散列方法方面处于领先地位...

      //for classes that contain a single int value
      return this.value;
      
      //for classes that contain multiple int value
      return x ^ y;
      
      //for classes that contain single number bigger than int    
      return ((int)value ^ (int)(value >> 32)); 
      
      //for classes that contain class instance fields which inherit from object
      return obj1.GetHashCode();
      
      //for classes that contain multiple class instance fields which inherit from object
      return obj1.GetHashCode() ^ obj2.GetHashCode() ^ obj3.GetHashCode(); 
      

      我猜想对于多个 big int 你可以使用这个:

      int a=((int)value1 ^ (int)(value1 >> 32));
      int b=((int)value2 ^ (int)(value2 >> 32));
      int c=((int)value3 ^ (int)(value3 >> 32));
      return a ^ b ^ c;
      

      对于多类型也是如此:首先使用GetHashCode()全部转换为int 然后 int 值将被异或,结果是你的哈希。

      对于那些使用hash作为ID的人(我的意思是一个唯一值),hash自然是限制在一个数字的,我认为hash算法是5个字节,至少MD5。

      您可以将多个值转换为一个散列值,其中一些是相同的,因此不要将其用作标识符。 (也许有一天我会使用你的组件)

      【讨论】:

      • 异或整数以生成哈希码是一种众所周知的反模式,它往往会导致与实际值发生特别多的冲突。
      • 这里的每个人都使用整数,并且从来没有任何形式的哈希值相同的保证,它只是试图尽可能多地发生冲突。
      • 是的,但是你的第二个和第五个不要试图避免碰撞。
      • 是的,这种反模式很常见。
      • 有一个平衡点。使用像 Spookyhash 这样非常好的哈希码,您将获得更好的碰撞避免,但它的计算时间比任何这些都多(但是当涉及到大量数据的哈希时,Spookyhash 非常快)。在异或之前对其中一个值进行简单的移位只是很好地减少碰撞的边际额外成本。质数乘法再次增加了时间和质量。因此,在 shift 或 mult 之间哪个更好是有争议的。普通异或虽然经常在真实数据上发生很多冲突,但最好避免
      【解决方案18】:

      我在使用上面选择的实现时遇到了浮点数和小数的问题。

      此测试失败(浮点数;即使我将 2 个值切换为负数,哈希也是相同的):

              var obj1 = new { A = 100m, B = 100m, C = 100m, D = 100m};
              var obj2 = new { A = 100m, B = 100m, C = -100m, D = -100m};
              var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);
              var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);
              Assert.IsFalse(hash1 == hash2, string.Format("Hashcode values should be different   hash1:{0}  hash2:{1}",hash1,hash2));
      

      但是这个测试通过了(使用整数):

              var obj1 = new { A = 100m, B = 100m, C = 100, D = 100};
              var obj2 = new { A = 100m, B = 100m, C = -100, D = -100};
              var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);
              var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);
              Assert.IsFalse(hash1 == hash2, string.Format("Hashcode values should be different   hash1:{0}  hash2:{1}",hash1,hash2));
      

      我将实现更改为不对原始类型使用 GetHashCode,它似乎工作得更好

          private static int InternalComputeHash(params object[] obj)
          {
              unchecked
              {
                  var result = (int)SEED_VALUE_PRIME;
                  for (uint i = 0; i < obj.Length; i++)
                  {
                      var currval = result;
                      var nextval = DetermineNextValue(obj[i]);
                      result = (result * MULTIPLIER_VALUE_PRIME) + nextval;
      
                  }
                  return result;
              }
          }
      
      
      
          private static int DetermineNextValue(object value)
          {
              unchecked
              {
      
                      int hashCode;
                      if (value is short
                          || value is int
                          || value is byte
                          || value is sbyte
                          || value is uint
                          || value is ushort
                          || value is ulong
                          || value is long
                          || value is float
                          || value is double
                          || value is decimal)
                      {
                          return Convert.ToInt32(value);
                      }
                      else
                      {
                          return value != null ? value.GetHashCode() : 0;
                      }
              }
          }
      

      【讨论】:

      • 如果您有其他意图,unchecked 不会影响 Convert.ToInt32uintlongfloatdoubledecimal 都可以在此处溢出。
      【解决方案19】:

      这是一个静态帮助类,实现了 Josh Bloch 的实现;并提供显式重载来“防止”装箱,并专门为长原语实现散列。

      您可以传递与您的 equals 实现匹配的字符串比较。

      由于 Hash 输出始终是 int,因此您可以将 Hash 调用链接起来。

      using System;
      using System.Collections;
      using System.Collections.Generic;
      using System.Reflection;
      using System.Runtime.CompilerServices;
      
      
      namespace Sc.Util.System
      {
          /// <summary>
          /// Static methods that allow easy implementation of hashCode. Example usage:
          /// <code>
          /// public override int GetHashCode()
          ///     => HashCodeHelper.Seed
          ///         .Hash(primitiveField)
          ///         .Hsh(objectField)
          ///         .Hash(iEnumerableField);
          /// </code>
          /// </summary>
          public static class HashCodeHelper
          {
              /// <summary>
              /// An initial value for a hashCode, to which is added contributions from fields.
              /// Using a non-zero value decreases collisions of hashCode values.
              /// </summary>
              public const int Seed = 23;
      
              private const int oddPrimeNumber = 37;
      
      
              /// <summary>
              /// Rotates the seed against a prime number.
              /// </summary>
              /// <param name="aSeed">The hash's first term.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              private static int rotateFirstTerm(int aSeed)
              {
                  unchecked {
                      return HashCodeHelper.oddPrimeNumber * aSeed;
                  }
              }
      
      
              /// <summary>
              /// Contributes a boolean to the developing HashCode seed.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aBoolean">The value to contribute.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash(this int aSeed, bool aBoolean)
              {
                  unchecked {
                      return HashCodeHelper.rotateFirstTerm(aSeed)
                              + (aBoolean
                                      ? 1
                                      : 0);
                  }
              }
      
              /// <summary>
              /// Contributes a char to the developing HashCode seed.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aChar">The value to contribute.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash(this int aSeed, char aChar)
              {
                  unchecked {
                      return HashCodeHelper.rotateFirstTerm(aSeed)
                              + aChar;
                  }
              }
      
              /// <summary>
              /// Contributes an int to the developing HashCode seed.
              /// Note that byte and short are handled by this method, through implicit conversion.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aInt">The value to contribute.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash(this int aSeed, int aInt)
              {
                  unchecked {
                      return HashCodeHelper.rotateFirstTerm(aSeed)
                              + aInt;
                  }
              }
      
              /// <summary>
              /// Contributes a long to the developing HashCode seed.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aLong">The value to contribute.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash(this int aSeed, long aLong)
              {
                  unchecked {
                      return HashCodeHelper.rotateFirstTerm(aSeed)
                              + (int)(aLong ^ (aLong >> 32));
                  }
              }
      
              /// <summary>
              /// Contributes a float to the developing HashCode seed.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aFloat">The value to contribute.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash(this int aSeed, float aFloat)
              {
                  unchecked {
                      return HashCodeHelper.rotateFirstTerm(aSeed)
                              + Convert.ToInt32(aFloat);
                  }
              }
      
              /// <summary>
              /// Contributes a double to the developing HashCode seed.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aDouble">The value to contribute.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash(this int aSeed, double aDouble)
                  => aSeed.Hash(Convert.ToInt64(aDouble));
      
              /// <summary>
              /// Contributes a string to the developing HashCode seed.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aString">The value to contribute.</param>
              /// <param name="stringComparison">Optional comparison that creates the hash.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash(
                      this int aSeed,
                      string aString,
                      StringComparison stringComparison = StringComparison.Ordinal)
              {
                  if (aString == null)
                      return aSeed.Hash(0);
                  switch (stringComparison) {
                      case StringComparison.CurrentCulture :
                          return StringComparer.CurrentCulture.GetHashCode(aString);
                      case StringComparison.CurrentCultureIgnoreCase :
                          return StringComparer.CurrentCultureIgnoreCase.GetHashCode(aString);
                      case StringComparison.InvariantCulture :
                          return StringComparer.InvariantCulture.GetHashCode(aString);
                      case StringComparison.InvariantCultureIgnoreCase :
                          return StringComparer.InvariantCultureIgnoreCase.GetHashCode(aString);
                      case StringComparison.OrdinalIgnoreCase :
                          return StringComparer.OrdinalIgnoreCase.GetHashCode(aString);
                      default :
                          return StringComparer.Ordinal.GetHashCode(aString);
                  }
              }
      
              /// <summary>
              /// Contributes a possibly-null array to the developing HashCode seed.
              /// Each element may be a primitive, a reference, or a possibly-null array.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aArray">CAN be null.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash(this int aSeed, IEnumerable aArray)
              {
                  if (aArray == null)
                      return aSeed.Hash(0);
                  int countPlusOne = 1; // So it differs from null
                  foreach (object item in aArray) {
                      ++countPlusOne;
                      if (item is IEnumerable arrayItem) {
                          if (!object.ReferenceEquals(aArray, arrayItem))
                              aSeed = aSeed.Hash(arrayItem); // recursive call!
                      } else
                          aSeed = aSeed.Hash(item);
                  }
                  return aSeed.Hash(countPlusOne);
              }
      
              /// <summary>
              /// Contributes a possibly-null array to the developing HashCode seed.
              /// You must provide the hash function for each element.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aArray">CAN be null.</param>
              /// <param name="hashElement">Required: yields the hash for each element
              /// in <paramref name="aArray"/>.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash<T>(this int aSeed, IEnumerable<T> aArray, Func<T, int> hashElement)
              {
                  if (aArray == null)
                      return aSeed.Hash(0);
                  int countPlusOne = 1; // So it differs from null
                  foreach (T item in aArray) {
                      ++countPlusOne;
                      aSeed = aSeed.Hash(hashElement(item));
                  }
                  return aSeed.Hash(countPlusOne);
              }
      
              /// <summary>
              /// Contributes a possibly-null object to the developing HashCode seed.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="aObject">CAN be null.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int Hash(this int aSeed, object aObject)
              {
                  switch (aObject) {
                      case null :
                          return aSeed.Hash(0);
                      case bool b :
                          return aSeed.Hash(b);
                      case char c :
                          return aSeed.Hash(c);
                      case int i :
                          return aSeed.Hash(i);
                      case long l :
                          return aSeed.Hash(l);
                      case float f :
                          return aSeed.Hash(f);
                      case double d :
                          return aSeed.Hash(d);
                      case string s :
                          return aSeed.Hash(s);
                      case IEnumerable iEnumerable :
                          return aSeed.Hash(iEnumerable);
                  }
                  return aSeed.Hash(aObject.GetHashCode());
              }
      
      
              /// <summary>
              /// This utility method uses reflection to iterate all specified properties that are readable
              /// on the given object, excluding any property names given in the params arguments, and
              /// generates a hashcode.
              /// </summary>
              /// <param name="aSeed">The developing hash code, or the seed: if you have no seed, use
              /// the <see cref="Seed"/>.</param>
              /// <param name="aObject">CAN be null.</param>
              /// <param name="propertySelector"><see cref="BindingFlags"/> to select the properties to hash.</param>
              /// <param name="ignorePropertyNames">Optional.</param>
              /// <returns>A hash from the properties contributed to <c>aSeed</c>.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int HashAllProperties(
                      this int aSeed,
                      object aObject,
                      BindingFlags propertySelector
                              = BindingFlags.Instance
                              | BindingFlags.Public
                              | BindingFlags.GetProperty,
                      params string[] ignorePropertyNames)
              {
                  if (aObject == null)
                      return aSeed.Hash(0);
                  if ((ignorePropertyNames != null)
                          && (ignorePropertyNames.Length != 0)) {
                      foreach (PropertyInfo propertyInfo in aObject.GetType()
                              .GetProperties(propertySelector)) {
                          if (!propertyInfo.CanRead
                                  || (Array.IndexOf(ignorePropertyNames, propertyInfo.Name) >= 0))
                              continue;
                          aSeed = aSeed.Hash(propertyInfo.GetValue(aObject));
                      }
                  } else {
                      foreach (PropertyInfo propertyInfo in aObject.GetType()
                              .GetProperties(propertySelector)) {
                          if (propertyInfo.CanRead)
                              aSeed = aSeed.Hash(propertyInfo.GetValue(aObject));
                      }
                  }
                  return aSeed;
              }
      
      
              /// <summary>
              /// NOTICE: this method is provided to contribute a <see cref="KeyValuePair{TKey,TValue}"/> to
              /// the developing HashCode seed; by hashing the key and the value independently. HOWEVER,
              /// this method has a different name since it will not be automatically invoked by
              /// <see cref="Hash(int,object)"/>, <see cref="Hash(int,IEnumerable)"/>,
              /// or <see cref="HashAllProperties"/> --- you MUST NOT mix this method with those unless
              /// you are sure that no KeyValuePair instances will be passed to those methods; or otherwise
              /// the generated hash code will not be consistent. This method itself ALSO will not invoke
              /// this method on the Key or Value here if that itself is a KeyValuePair.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="keyValuePair">The value to contribute.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int HashKeyAndValue<TKey, TValue>(this int aSeed, KeyValuePair<TKey, TValue> keyValuePair)
                  => aSeed.Hash(keyValuePair.Key)
                          .Hash(keyValuePair.Value);
      
              /// <summary>
              /// NOTICE: this method is provided to contribute a collection of <see cref="KeyValuePair{TKey,TValue}"/>
              /// to the developing HashCode seed; by hashing the key and the value independently. HOWEVER,
              /// this method has a different name since it will not be automatically invoked by
              /// <see cref="Hash(int,object)"/>, <see cref="Hash(int,IEnumerable)"/>,
              /// or <see cref="HashAllProperties"/> --- you MUST NOT mix this method with those unless
              /// you are sure that no KeyValuePair instances will be passed to those methods; or otherwise
              /// the generated hash code will not be consistent. This method itself ALSO will not invoke
              /// this method on a Key or Value here if that itself is a KeyValuePair or an Enumerable of
              /// KeyValuePair.
              /// </summary>
              /// <param name="aSeed">The developing HashCode value or seed.</param>
              /// <param name="keyValuePairs">The values to contribute.</param>
              /// <returns>The new hash code.</returns>
              [MethodImpl(MethodImplOptions.AggressiveInlining)]
              public static int HashKeysAndValues<TKey, TValue>(
                      this int aSeed,
                      IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)
              {
                  if (keyValuePairs == null)
                      return aSeed.Hash(null);
                  foreach (KeyValuePair<TKey, TValue> keyValuePair in keyValuePairs) {
                      aSeed = aSeed.HashKeyAndValue(keyValuePair);
                  }
                  return aSeed;
              }
          }
      }
      

      【讨论】:

      • Yipes:我发现了一个错误! HashKeysAndValues 方法已修复:它调用 HashKeyAndValue
      【解决方案20】:

      如果您想从 netstandard2.1 填充 HashCode

      public static class HashCode
      {
          public static int Combine(params object[] instances)
          {
              int hash = 17;
      
              foreach (var i in instances)
              {
                  hash = unchecked((hash * 31) + (i?.GetHashCode() ?? 0));
              }
      
              return hash;
          }
      }
      

      注意:如果和struct一起使用,会因为装箱而分配内存

      【讨论】:

        【解决方案21】:

        可以尝试采用 C++ Boost 库中的方法。像这样的:

        class HashUtil
        {
          public static int HashCombine(int seed, int other)
          {
            unchecked
            {
              return other + 0x9e3779b9 + (seed << 6) + (seed >> 2);
            }
          }
        }
        

        然后:

        class MyClass
        {
          private string _field1;
          private int _field2;
          private AnotherClass _field3;
          private YetAnotherClass _field4;
        
          public override int GetHashCode()
          {
            int result = HashUtil.HashCombine(_field1.GetHashCode(), _field2);
            result = HashUtil.HashCombine(result, _field3.GetHashCode());
            return HashUtil.HashCombine(result, _field4.GetHashCode());
          }
        }
        

        【讨论】:

          【解决方案22】:

          我想将我的最新发现添加到我经常回来的这个帖子中。

          我当前的视觉工作室/项目设置提供了自动将元组重构为结构的功能。这将生成一个 GetHashCode 函数,如下所示:

                  public override int GetHashCode()
                  {
                      int hashCode = -2088324004;
                      hashCode = hashCode * -1521134295 + AuftragGesperrt.GetHashCode();
                      hashCode = hashCode * -1521134295 + Auftrag_gesperrt_von.GetHashCode();
                      hashCode = hashCode * -1521134295 + Auftrag_gesperrt_am.GetHashCode();
                      return hashCode;
                  }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-05-13
            • 1970-01-01
            • 2011-06-09
            • 2011-02-13
            • 2011-12-06
            • 1970-01-01
            • 2012-07-13
            相关资源
            最近更新 更多