【问题标题】:HashSet with a custom struct allocates heavy with Contains function具有自定义结构的 HashSet 使用 Contains 函数分配重
【发布时间】:2014-03-27 19:49:11
【问题描述】:

我正在使用HashSet 集合类型,它已经显着提高了我的算法的性能。似乎每次我调用myHashSet.Contains(someValue) 时,内部实现都会在调用Equals 之前立即对值类型进行装箱。

在使用值类型时,有没有办法避免这些浪费的分配?

示例代码:

public struct TestStruct {
    public int a;
    public int b;

    public override int GetHashCode() {
        return a ^ b;
    }

    public override bool Equals(object obj) {
        if (!(obj is TestStruct))
            return false;
        TestStruct other = (TestStruct)obj;
        return a == other.a && b == other.b;
    }
}

var hashset = new HashSet<TestStruct>();
PopulateSet(hashset);

// About to go crazy on the allocations...
if (hashset.Contains(someValue)) { ... }
// Lots of allocations just happened :(

【问题讨论】:

    标签: c# .net mono unity3d hashset


    【解决方案1】:

    经过幸运的猜测,答案似乎只是实现IEquatable&lt;T&gt; 接口,如下所示。 HashSet&lt;T&gt;(或至少是 Mono 实现)然后通过使用不同的比较器实现对其 Contains 方法采用免分配方法。

    public struct TestStruct : IEquatable<TestStruct> {
        ...
    
        public bool Equals(TestStruct other) {
            return a == other.a && b == other.b;
        }
    }
    
    // No more pain!
    if (hashset.Contains(someValue)) { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-12
      • 2019-03-18
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 2017-02-21
      • 1970-01-01
      • 2017-08-11
      相关资源
      最近更新 更多