【发布时间】: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