<p>Say I have an object that stores a byte array and I want to be able to efficiently generate a hashcode for it. I've used the cryptographic hash functions for this in the past because they are easy to implement, but they are doing a lot more work than they should to be cryptographically oneway, and I don't care about that (I'm just using the hashcode as a key into a hashtable).</p>

<p>Here's what I have today:</p>

<pre><code>struct SomeData : IEquatable&lt;SomeData&gt;
{
    private readonly byte[] data;
    public SomeData(byte[] data)
    {
        if (null == data || data.Length &lt;= 0)
        {
            throw new ArgumentException("data");
        }
        this.data = new byte[data.Length];
        Array.Copy(data, this.data, data.Length);
    }

    public override bool Equals(object obj)
    {
        return obj is SomeData &amp;&amp; Equals((SomeData)obj);
    }

    public bool Equals(SomeData other)
    {
        if (other.data.Length != data.Length)
        {
            return false;
        }
        for (int i = 0; i &lt; data.Length; ++i)
        {
            if (data[i] != other.data[i])
            {
                return false;
            }
        }
        return true;
    }
    public override int GetHashCode()
    {
        return BitConverter.ToInt32(new MD5CryptoServiceProvider().ComputeHash(data), 0);
    }
}
</code></pre>

<p>Any thoughts?</p>

<hr>

<p>dp: You are right that I missed a check in Equals, I have updated it.  Using the existing hashcode from the byte array will result in reference equality (or at least that same concept translated to hashcodes).
for example:</p>

<pre><code>byte[] b1 = new byte[] { 1 };
byte[] b2 = new byte[] { 1 };
int h1 = b1.GetHashCode();
int h2 = b2.GetHashCode();
</code></pre>

<p>With that code, despite the two byte arrays having the same values within them, they are referring to different parts of memory and will result in (probably) different hash codes. I need the hash codes for two byte arrays with the same contents to be equal.</p>

[{'answer_id': 16378, 'author': 'fulmicoton', 'author_id': 446497, 'author_profile': 'https://Stackoverflow.com/users/446497', 'pm_score': 2, 'selected': False, 'text': '<p>If you are looking for performance, I tested a few hash keys, and \nI recommend <a href="http://burtleburtle.net/bob/hash/doobs.html" rel="nofollow noreferrer">Bob Jenkin\'s hash function</a>. It is both crazy fast\nto compute and will give as few collisions as the cryptographic\nhash you used until now.</p>\n\n<p>I don\'t know C# at all, and I don\'t know if it can link with C, but\nhere is <a href="http://burtleburtle.net/bob/c/lookup3.c" rel="nofollow noreferrer">its implementation in C</a>.</p>\n'}, {'answer_id': 16381, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 6, 'selected': False, 'text': "<p>The hash code of an object does not need to be unique. </p>\n\n<p>The checking rule is: </p>\n\n<ul>\n<li>Are the hash codes equal? Then call the full (slow) <code>Equals</code> method.</li>\n<li>Are the hash codes not equal? Then the two items are definitely not equal.</li>\n</ul>\n\n<p>All you want is a <code>GetHashCode</code> algorithm that splits up your collection into roughly even groups - it shouldn't form the key as the <code>HashTable</code> or <code>Dictionary&lt;&gt;</code> will need to use the hash to optimise retrieval.</p>\n\n<p>How long do you expect the data to be? How random? If lengths vary greatly (say for files) then just return the length.  If lengths are likely to be similar look at a subset of the bytes that varies.</p>\n\n<p><code>GetHashCode</code> should be a lot quicker than <code>Equals</code>, but doesn't need to be unique.</p>\n\n<p>Two identical things <em>must never</em> have different hash codes. Two different objects <em>should not</em> have the same hash code, but some collisions are to be expected (after all, there are more permutations than possible 32 bit integers).</p>\n"}, {'answer_id': 16387, 'author': 'denis phillips', 'author_id': 748, 'author_profile': 'https://Stackoverflow.com/users/748', 'pm_score': 1, 'selected': False, 'text': '<p>Is using the existing hashcode from the byte array field not good enough? Also note that in the Equals method you should check that the arrays are the same size before doing the compare.</p>\n'}, {'answer_id': 16408, 'author': 'Lee', 'author_id': 1954, 'author_profile': 'https://Stackoverflow.com/users/1954', 'pm_score': 1, 'selected': False, 'text': "<p>Generating a good hash is easier said than done.  Remember, you're basically representing n bytes of data with m bits of information.  The larger your data set and the smaller m is, the more likely you'll get a collision ... two pieces of data resolving to the same hash.</p>\n\n<p>The simplest hash I ever learned was simply XORing all the bytes together.  It's easy, faster than most complicated hash algorithms and a halfway decent general-purpose hash algorithm for small data sets.  It's the Bubble Sort of hash algorithms really.  Since the simple implementation would leave you with 8 bits, that's only 256 hashes ... not so hot.  You could XOR chunks instead of individal bytes, but then the algorithm gets much more complicated.</p>\n\n<p>So certainly, the cryptographic algorithms are maybe doing some stuff you don't need ... but they're also a huge step up in general-purpose hash quality.  The MD5 hash you're using has 128 bits, with billions and billions of possible hashes.  The only way you're likely to get something better is to take some representative samples of the data you expect to be going through your application and try various algorithms on it to see how many collisions you get.</p>\n\n<p>So until I see some reason to not use a canned hash algorithm (performance, perhaps?), I'm going to have to recommend you stick with what you've got.</p>\n"}, {'answer_id': 16448, 'author': 'Jon Galloway', 'author_id': 5, 'author_profile': 'https://Stackoverflow.com/users/5', 'pm_score': 2, 'selected': False, 'text': '<p>Have you compared with the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1cryptoserviceprovider.computehash.aspx" rel="nofollow noreferrer">SHA1CryptoServiceProvider.ComputeHash</a> method? It takes a byte array and returns a SHA1 hash, and I believe it\'s pretty well optimized. I used it in an <a href="http://www.codeplex.com/Identicon/SourceControl/FileView.aspx?itemId=63541&amp;changeSetId=3301" rel="nofollow noreferrer">Identicon Handler</a> that performed pretty well under load.</p>\n'}, {'answer_id': 17348, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.gethashcode.aspx" rel="nofollow noreferrer">RuntimeHelpers.GetHashCode</a> might help:</p>\n\n<blockquote>\n  <p>From Msdn:</p>\n  \n  <p>Serves as a hash function for a\n  particular type, suitable for use in\n  hashing algorithms and data structures\n  such as a hash table.</p>\n</blockquote>\n'}, {'answer_id': 53056, 'author': 'Oskar', 'author_id': 5472, 'author_profile': 'https://Stackoverflow.com/users/5472', 'pm_score': 1, 'selected': False, 'text': "<p>Whether you want a perfect hashfunction (different value for each object that evaluates to equal) or just a pretty good one is always a performance tradeoff, it takes normally time to compute a good hashfunction and if your dataset is smallish you're better of with a fast function. The most important (as your second post points out) is correctness, and to achieve that all you need is to return the Length of the array. Depending on your dataset that might even be ok. If it isn't (say all your arrays are equally long) you can go with something cheap like looking at the first and last value and XORing their values and then add more complexity as you see fit for your data. </p>\n\n<p>A quick way to see how your hashfunction performs on your data is to add all the data to a hashtable and count the number of times the Equals function gets called, if it is too often you have more work to do on the function. If you do this just keep in mind that the hashtable's size needs to be set bigger than your dataset when you start, otherwise you are going to rehash the data which will trigger reinserts and more Equals evaluations (though possibly more realistic?)</p>\n\n<p>For some objects (not this one) a quick HashCode can be generated by ToString().GetHashCode(), certainly not optimal, but useful as people tend to return something close to the identity of the object from ToString() and that is exactly what GetHashcode is looking for</p>\n\n<p>Trivia: The worst performance I have ever seen was when someone by mistake returned a constant from GetHashCode, easy to spot with a debugger though, especially if you do lots of lookups in your hashtable</p>\n"}, {'answer_id': 425184, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Borrowing from the code generated by JetBrains software, I have settled on this function:</p>\n\n<pre><code>    public override int GetHashCode()\n    {\n        unchecked\n        {\n            var result = 0;\n            foreach (byte b in _key)\n                result = (result*31) ^ b;\n            return result;\n        }\n    }\n</code></pre>\n\n<p>The problem with just XOring the bytes is that 3/4 (3 bytes) of the returned value has only 2 possible values (all on or all off).  This spreads the bits around a little more.</p>\n\n<p>Setting a breakpoint in Equals was a good suggestion.  Adding about 200,000 entries of my data to a Dictionary, sees about 10 Equals calls (or 1/20,000).</p>\n'}, {'answer_id': 468084, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': '<p>Don\'t use cryptographic hashes for a hashtable, that\'s ridiculous/overkill.</p>\n\n<p>Here ya go... Modified FNV Hash in C#</p>\n\n<p><a href="http://bretm.home.comcast.net/hash/6.html" rel="noreferrer">http://bretm.home.comcast.net/hash/6.html</a></p>\n\n<pre><code>    public static int ComputeHash(params byte[] data)\n    {\n        unchecked\n        {\n            const int p = 16777619;\n            int hash = (int)2166136261;\n\n            for (int i = 0; i &lt; data.Length; i++)\n                hash = (hash ^ data[i]) * p;\n\n            hash += hash &lt;&lt; 13;\n            hash ^= hash &gt;&gt; 7;\n            hash += hash &lt;&lt; 3;\n            hash ^= hash &gt;&gt; 17;\n            hash += hash &lt;&lt; 5;\n            return hash;\n        }\n    }\n</code></pre>\n'}, {'answer_id': 22363320, 'author': 'Tono Nam', 'author_id': 637142, 'author_profile': 'https://Stackoverflow.com/users/637142', 'pm_score': 2, 'selected': False, 'text': '<p>I found interesting results:</p>\n\n<p>I have the class:</p>\n\n<pre><code>public class MyHash : IEquatable&lt;MyHash&gt;\n{        \n    public byte[] Val { get; private set; }\n\n    public MyHash(byte[] val)\n    {\n        Val = val;\n    }\n\n    /// &lt;summary&gt;\n    /// Test if this Class is equal to another class\n    /// &lt;/summary&gt;\n    /// &lt;param name="other"&gt;&lt;/param&gt;\n    /// &lt;returns&gt;&lt;/returns&gt;\n    public bool Equals(MyHash other)\n    {\n        if (other.Val.Length == this.Val.Length)\n        {\n            for (var i = 0; i &lt; this.Val.Length; i++)\n            {\n                if (other.Val[i] != this.Val[i])\n                {\n                    return false;\n                }\n            }\n\n            return true;\n        }\n        else\n        {\n            return false;\n        }            \n    }\n\n    public override int GetHashCode()\n    {            \n        var str = Convert.ToBase64String(Val);\n        return str.GetHashCode();          \n    }\n}\n</code></pre>\n\n<p>Then I created a dictionary with keys of type MyHash in order to test how fast I can insert and I can also know how many collisions there are. I did the following</p>\n\n<pre><code>        // dictionary we use to check for collisions\n        Dictionary&lt;MyHash, bool&gt; checkForDuplicatesDic = new Dictionary&lt;MyHash, bool&gt;();\n\n        // used to generate random arrays\n        Random rand = new Random();\n\n\n\n        var now = DateTime.Now;\n\n        for (var j = 0; j &lt; 100; j++)\n        {\n            for (var i = 0; i &lt; 5000; i++)\n            {\n                // create new array and populate it with random bytes\n                byte[] randBytes = new byte[byte.MaxValue];\n                rand.NextBytes(randBytes);\n\n                MyHash h = new MyHash(randBytes);\n\n                if (checkForDuplicatesDic.ContainsKey(h))\n                {\n                    Console.WriteLine("Duplicate");\n                }\n                else\n                {\n                    checkForDuplicatesDic[h] = true;\n                }\n            }\n            Console.WriteLine(j);\n            checkForDuplicatesDic.Clear(); // clear dictionary every 5000 iterations\n        }\n\n        var elapsed = DateTime.Now - now;\n\n        Console.Read();\n</code></pre>\n\n<p>Every time I insert a new item to the dictionary the dictionary will calculate the hash of that object. So you can tell what method is most efficient by placing several answers found in here in the method <code>public override int GetHashCode()</code> The method that was by far the fastest and had the least number of collisions was:</p>\n\n<pre><code>    public override int GetHashCode()\n    {            \n        var str = Convert.ToBase64String(Val);\n        return str.GetHashCode();          \n    }\n</code></pre>\n\n<p>that took 2 seconds to execute. The method</p>\n\n<pre><code>    public override int GetHashCode()\n    {\n        // 7.1 seconds\n        unchecked\n        {\n            const int p = 16777619;\n            int hash = (int)2166136261;\n\n            for (int i = 0; i &lt; Val.Length; i++)\n                hash = (hash ^ Val[i]) * p;\n\n            hash += hash &lt;&lt; 13;\n            hash ^= hash &gt;&gt; 7;\n            hash += hash &lt;&lt; 3;\n            hash ^= hash &gt;&gt; 17;\n            hash += hash &lt;&lt; 5;\n            return hash;\n        }\n    }\n</code></pre>\n\n<p><strong>had no collisions also but it took 7 seconds to execute!</strong></p>\n'}, {'answer_id': 25558241, 'author': 'Varty', 'author_id': 2519526, 'author_profile': 'https://Stackoverflow.com/users/2519526', 'pm_score': 0, 'selected': False, 'text': '<pre><code>private int? hashCode;\n\npublic override int GetHashCode()\n{\n    if (!hashCode.HasValue)\n    {\n        var hash = 0;\n        for (var i = 0; i &lt; bytes.Length; i++)\n        {\n            hash = (hash &lt;&lt; 4) + bytes[i];\n        }\n        hashCode = hash;\n    }\n    return hashCode.Value;\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/16340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1948/']