我想减少代码执行时间。查看一些测试结果,我发现 GetHashCode() 占用了我 21.62% 的执行时间。
我还收到警告:
Warning 1 DA0010: .*.GetHashCode() = 7,63; GetHashCode functions should be cheap and not allocate any memory. Reduce complexity of hash code function if possible.
代码片段:
我在 Field 类中的 GetHashCode():
public override int GetHashCode()
{
int hash = 7;
hash = (hash * 13) + this.Coordinate.GetHashCode();
return hash;
}
坐标类中我的 GetHashCode():
public override int GetHashCode()
{
int hash = 17;
hash = (hash * 23) + this.Row.GetHashCode();
hash = (hash * 23) + this.Column.GetHashCode();
return hash;
}
编辑:行和列只是字节变量。我只是调用他们的属性,该属性在 get 访问器中返回一个字节
数独类中我的 GetHashCode():
public override int GetHashCode()
{
int hash = 7;
hash = (hash * 5) + this.Grid.GetHashCode();
return hash;
}
编辑:网格只是一个类型为:Field[,]
的多维数组,我在这里称之为属性,它通过它的 get 返回一个 Field[,] 网格访问器。
问题:如何大幅降低 GetHashCode() 的复杂性并提高其性能?为什么GetHashCode()方法的性能这么低?
最佳答案
我怀疑您会发现 GetHashCode
不是您的问题。如果您花费超过 20% 的时间在 GetHashCode
上,那么您一定进行了大量的字典查找。或者您正在将哈希码用于您可能不应该使用它的东西。
GetHashCode
可能是性能问题的表现,但几乎可以肯定不是原因。
关于c# - 如何降低GetHashCode的复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15500865/