Improve ArraySegment's override of GetHashCode (#4654)
authorJames Ko <jamesqko@gmail.com>
Sat, 22 Oct 2016 01:21:27 +0000 (21:21 -0400)
committerJan Kotas <jkotas@microsoft.com>
Sat, 22 Oct 2016 01:21:27 +0000 (18:21 -0700)
* Improve ArraySegment's override of GetHashCode

* Use new implementation suggested by @VSadov

* Respond to PR feedback

* Remove the workaround for object.GetHashCode

* Respond to HashHelpers changes

* Fix compile errors.

src/mscorlib/src/System/ArraySegment.cs

index 95254bf..1e76d17 100644 (file)
@@ -112,9 +112,19 @@ namespace System
         
         public override int GetHashCode()
         {
-            return null == _array
-                        ? 0
-                        : _array.GetHashCode() ^ _offset ^ _count;
+            if (_array == null)
+            {
+                return 0;
+            }
+            
+            int hash = 5381;
+            hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset);
+            hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count);
+            
+            // The array hash is expected to be an evenly-distributed mixture of bits,
+            // so rather than adding the cost of another rotation we just xor it.
+            hash ^= _array.GetHashCode();
+            return hash;
         }
 
         public override bool Equals(Object obj)