I have some code i'm revewing, which is used to convert some text into an MD5 Hash
. Works great. It's used to create an MD5Hhash
for a gravatar avatar. Here it is :-
static MD5CryptoServiceProvider md5CryptoServiceProvider = null;
public static string ToMD5Hash(this string value)
{
//creating only when needed
if (md5CryptoServiceProvider == null)
{
md5CryptoServiceProvider = new MD5CryptoServiceProvider();
}
byte[] newdata = Encoding.Default.GetBytes(value);
byte[] encrypted = md5CryptoServiceProvider.ComputeHash(newdata);
return BitConverter.ToString(encrypted).Replace("-", "").ToLower();
}
Notice how we create a MD5CryptoServiceProvider
the first time this method is called? (lets not worry about race-conditions here, for simplicity).
I was wondering, is it more computationally expensive if i change the lines that are used to create the provider, to this...
using(var md5CryptoServiceProvider = new MD5CryptoServiceProvider())
{
... snip snip snip ....
}
Now, how is this method used/consumed? Well, imagine it's the home page of StackOverflow -> for each post, generate an md5 hash of the user, so we can generate their gravatar url. So the view could call this method a few dozen times.
Without trying to waste too much time stressing over premature optimzation, etc ... which would be better?