Examine the string GetHashCode method and analyze its performance characteristics.
GetHashCode. This method implements hashing in the .NET Framework. We look at the string GetHashCode virtual method implementation.Virtual
Notes, implementation. GetHashCode is located in mscorlib. It uses unsafe code (with shifts and bitwise operations) to compute well-distributed hash codes.Unsafe
An example. We can call GetHashCode on a string, but this usually doesn't do much good. This program shows how when we append a char to a string, the hash code keeps changing.Strings
So: The hash computation appears to be effective—no collisions are seen when we just append a character.
C# program that uses GetHashCode
static void Main()
string value = "";
for (int i = 0; i < 10; i++)
value += "x";
// This calls the unsafe code listed on this page.
Console.WriteLine("GETHASHCODE: " + value.GetHashCode());
Internal code. Here is a disassembled version of the intermediate language instructions that form the GetHashCode override method in the System.String type.
Tip: Hash codes are used in Dictionary instances and other associative collections.