Instead, you can always use an MD5 hash, which is relatively fast:
public string GetUrlHash(string url) { byte[] hash = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(url)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return sb.ToString(); }
Call it like this:
Console.WriteLine(this.GetUrlHash("http://stackoverflow.com/questions/5355003/storing-c-gethashcode-in-db-is-unreliable"));
And we get:
> 777BED7F83C66DAC111977067B4B4385
This should be reliable enough in terms of uniqueness. MD5 is currently unsafe for password-based applications, but you do not have this problem.
The only problem is using a row such as the primary key in the table can be problematic in terms of performance.
Another thing you can do is use the URL shortening approach: use the database sequence generation function and convert the value (make sure you use the LONG or BIGINT equivalent!) For something like Base36, which gives you a nice, short line .
source share