带有自定义结构的HashSet使用Contains函数分配重量

时间:2014-03-27 19:49:11

标签: c# .net mono unity3d hashset

我正在使用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 :(

1 个答案:

答案 0 :(得分:1)

幸运的猜测之后看起来答案就是实现IEquatable<T>界面,如下所示。 HashSet<T>(或至少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)) { ... }
相关问题