Can I depend on the values of GetHashCode() to be

2019-01-09 09:26发布

Is the return value of GetHashCode() guaranteed to be consistent assuming the same string value is being used? (C#/ASP.NET)

I uploaded my code to a server today and to my surprise I had to reindex some data because my server (win2008 64-bit) was returning different values compared to my desktop computer.

标签: c# hash
9条回答
\"骚年 ilove
2楼-- · 2019-01-09 10:15

I wonder if there are differences between 32-bit and 64-bit operating systems, because I am certain both my server and home computer are running the same version of .NET

I was always weary of using GetHashCode(), it might be a good idea for me to simply role my own hash algorithm. Well at least I ended up writing a quick re-index .aspx page because of it.

查看更多
乱世女痞
3楼-- · 2019-01-09 10:16
    /// <summary>
    /// Default implementation of string.GetHashCode is not consistent on different platforms (x32/x64 which is our case) and frameworks. 
    /// FNV-1a - (Fowler/Noll/Vo) is a fast, consistent, non-cryptographic hash algorithm with good dispersion. (see http://isthe.com/chongo/tech/comp/fnv/#FNV-1a)
    /// </summary>
    private static int GetFNV1aHashCode(string str)
    {
        if (str == null)
            return 0;
        var length = str.Length;
        // original FNV-1a has 32 bit offset_basis = 2166136261 but length gives a bit better dispersion (2%) for our case where all the strings are equal length, for example: "3EC0FFFF01ECD9C4001B01E2A707"
        int hash = length;
        for (int i = 0; i != length; ++i)
            hash = (hash ^ str[i]) * 16777619;
        return hash;
    }

This implementation can be slower than the unsafe one posted before. But much simpler and safe.

查看更多
We Are One
4楼-- · 2019-01-09 10:23

If I'm not mistaken, GetHashCode is consistent given the same value, but it is NOT guaranteed to be consistent across different versions of the framework.

From the MSDN docs on String.GetHashCode():

The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. A reason why this might happen is to improve the performance of GetHashCode.

查看更多
登录 后发表回答