c# - 如何降低GetHashCode的复杂度

标签 c# performance gethashcode

我想减少代码执行时间。查看一些测试结果,我发现 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/

相关文章:

c# - 为什么 'base' 对象的类型是我的具体类型?

c# - 小类的好散列? (覆盖 GetHashCode)

c# - 在 C# 中播种伪随机数生成器

c# - WCF HTTP 和 NamedPipe 服务

c++ - 反转数字的最有效方法

c# - 多重性与引用约束错误冲突

jquery - 使用 javascript 而非常规 anchor 移动到我网站中的其他页面

java - 寻找递归解的迭代解

c# - @Html.Action 正在从部分 View 镜像我的网站,而不引用布局页面?

c# - Polly RetryForever 没有重试