1: public static string GetMd5Hash(string input)
2: {
3: using (MD5 md5Hash = MD5.Create())
4: {
5: // Convert the input string to a byte array and compute the hash.
6: byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
7:
8: // Create a new Stringbuilder to collect the bytes
9: // and create a string.
10: StringBuilder sBuilder = new StringBuilder();
11:
12: // Loop through each byte of the hashed data
13: // and format each one as a hexadecimal string.
14: for (int i = 0; i < data.Length; i++)
15: {
16: sBuilder.Append(data[i].ToString("x2"));
17: }
18:
19: // Return the hexadecimal string.
20: return sBuilder.ToString();
21: }
22: }
这是一段 MSDN 官方的 MD5 示例,例子很简单且很容易理解。但是,这个例子也有很多的问题,首先上例至少创建了 3 个临时缓存区!且每次执行 GetMd5Hash 都会创建一个 MD5 实例,并在方法执行完成后释放它。这些都造成了很大的系统资源浪费和增加了 GC 的压力。
鉴于官方给的 Demo 并不优秀,且网上也没有给出很好使用方式,这里我就拿出我多年使用的 MD5 打开方式,这个方法同时支持 SHA1,SHA256 等,即支持 System.Security.Cryptography 命名空间下的 HashAlgorithm(哈希算法) 实现。也同时支持 .Net Framework 2.0 之后的所有 .Net 平台。
我不想看你的鬼废话,直接给我上最终代码》》》
先说明,这个文章是基于 System.Security.Cryptography 命名空间的实现,不是自己写一个 MD5 算法哦。
现在我们开始,首先我们先定义一个辅助类:
1: using System;
2: using System.Reflection;
3: using System.Runtime.CompilerServices;
4: using System.Security.Cryptography;
5:
6: static class THashAlgorithmInstances<THashAlgorithm> where THashAlgorithm : HashAlgorithm
7: {
8: /// <summary>
9: /// 线程静态变量。
10: /// 即:这个变量在每个线程中都是唯一的。
11: /// 再结合泛型类实现:该变量在不同泛型或不同的线程下的值都是不一样的。
12: /// 这样做的目的是为了避开多线程问题。
13: /// 关于垃圾回收:当 .NET 线程被释放时,程序中的所有线程静态变量都会被回收,GC 回收时同时将释放资源,所以不必担心释放问题,GC 会帮助我们的。
14: /// 这里描述的 .NET 线程释放不是指 .NET 线程回收至线程池。很多时候 .NET 的线程在程序关闭之前都不会真正释放,而是在线程池中继续驻留。
15: /// 线程唯一真的能避免多线程问题吗?答:多个线程所以用存储空间都不一样,那么脏值就不可能存在,如果这都能出现多线程问题,我直播吃....猪红(本人极其厌恶吃猪红)。
16: /// </summary>h
17: [ThreadStatic]
18: static THashAlgorithm instance;
19:
20: public static THashAlgorithm Instance => instance ?? Create();
21:
22: /// <summary>
23: /// 寻找 THashAlgorithm 类型下的 Create 静态方法,并执行它。
24: /// 如果没找到,则执行 Activator.CreateInstance 调用构造方法创建实例。
25: /// 如果 Activator.CreateInstance 方法执行失败,它会抛出异常。
26: /// </summary>
27: [MethodImpl(MethodImplOptions.NoInlining)]
28: static THashAlgorithm Create()
29: {
30: var createMethod = typeof(THashAlgorithm).GetMethod(
31: nameof(HashAlgorithm.Create), // 这段代码同 "Create",低版本 C# 可以替换掉
32: BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly,
33: Type.DefaultBinder,
34: Type.EmptyTypes,
35: null);
36:
37: if (createMethod != null)
38: {
39: instance = (THashAlgorithm)createMethod.Invoke(null, new object[] { });
40: }
41: else
42: {
43: instance = Activator.CreateInstance<THashAlgorithm>();
44: }
45:
46: return instance;
47: }
48: }
该辅助类帮助我们避开多线程问题,且帮助我们创建指定的 HashAlgorithm 实例。
这里说明一下,HashAlgorithm.ComputeHash (同 MD5.ComputeHash) 方法绝对不是线程安全的!大家使用它的时候必须要注意,在未线程同步下调用同一实例的 ComputeHash 方法得到的结果是错误的!
关于线程唯一和泛型唯一:
还记得老师教我们的时候强调静态变量就是唯一的,可是现在就突然出现了两个反例,与之对立,这让初学者一下子难以接受,其实这也很容易理解的:
首先 [ThreadStatic] 特性我们可以理解为将字段封装为了 ThreadLocal<T>,它在内部区分线程,然后返回不同的值。
然后泛型唯一,举例:我们都知道 List<int> 和 List<string> 它们不是一个类型!那么它们的字段 List<int>.thread_field 和 List<string>.thread_field 也同理不是一个字段,那么它们的值当然也不是同一个啦。
接下来我们再定义实现类:
1: public static class HashAlgorithmHelper
2: {
3: public static string ComputeHash<THashAlgorithm>(string input) where THashAlgorithm : HashAlgorithm
4: {
5: var data = THashAlgorithmInstances<THashAlgorithm>.Instance.ComputeHash(Encoding.UTF8.GetBytes(input));
6:
7: var sBuilder = new StringBuilder();
8:
9: foreach (var item in data)
10: {
11: sBuilder.Append(item.ToString("x2"));
12: }
13:
14: return sBuilder.ToString();
15: }
16: }
到这里我们入门级的 MD5 打开方式就完成了,使用方法:HashAlgorithmHelper.ComputeHash<MD5>("Hello World!")。
我们来先测试一下:
1: static void Main(string[] args)
2: {
3: Console.WriteLine(HashAlgorithmHelper.ComputeHash<MD5>("Hello World!"));
4: Console.WriteLine(GetMd5Hash("Hello World!"));
5:
6: while (true)
7: {
8: var stopwatch = Stopwatch.StartNew();
9:
10: for (int i = 0; i < 1000000; i++)
11: {
12: HashAlgorithmHelper.ComputeHash<MD5>("Hello World!");
13: }
14:
15: Console.WriteLine(stopwatch.ElapsedMilliseconds);
16:
17: stopwatch = Stopwatch.StartNew();
18:
19: for (int i = 0; i < 1000000; i++)
20: {
21: GetMd5Hash("Hello World!");
22: }
23:
24: Console.WriteLine(stopwatch.ElapsedMilliseconds);
25: }
26: }
输出结果:
可以看出我们的性能已经超官方 Demo 近一倍了。
接下来我们将进入进阶级打开方式,我们现在需要自己写一个简单的 byte[] To string 方法,我们先打开 C# 项目的 “允许不安全代码” 选项。
在解决方案中右键项目->属性->生成->勾选“允许不安全代码”。
然后我们在 HashAlgorithmHelper 类中定义新的 ToString 方法。
1: static string ToString(byte[] bytes)
2: {
3: unsafe
4: {
5: const int byte_len = 2; // 表示一个 byte 的字符长度。
6:
7: var str = new string('\0', byte_len * bytes.Length); // 创建一个指定长度的空字符串。
8:
9: fixed(char* pStr = str)
10: {
11: var pStr2 = pStr; // fixed pStr 是只读的,所以我们定义一个变量。
12:
13: foreach (var item in bytes)
14: {
15: *pStr2 = Digitals[item >> 4/* byte high */]; ++pStr2;
16: *pStr2 = Digitals[item & 15/* byte low */]; ++pStr2;
17: }
18: }
19:
20: return str;
21: }
22: }
然后我们修改 ComputeHash 方法为如下:
1: public static string ComputeHash<THashAlgorithm>(string input) where THashAlgorithm : HashAlgorithm
2: {
3: var bytes = Encoding.UTF8.GetBytes(input);
4:
5: var data = THashAlgorithmInstances<THashAlgorithm>.Instance.ComputeHash(bytes);
6:
7: return ToString(data);
8: }
现在我们再测试就会发现已经比官方 Demo 快 4 倍了!现在这个 MD5 打开方式已经适合绝大多数人了,如果您不喜欢不安全代码,也可以用数组代替,效率只差一丢丢而已,该方式我会在下方给出完整代码。
接下来我们使用 .Net Core 以最优的方式打开,我们修改 HashAlgorithmHelper 为如下:(这里就不再支持 .Net Framework 了)
1: public static class HashAlgorithmHelper
2: {
3: static readonly char[] Digitals = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
4:
5: // 在这个函数里要用到的 bytes 成员 ReadOnlySpan<byte> 与 byte[] 的一致,所以我们只需要修改参数类型即可。
6: static string ToString(ReadOnlySpan<byte> bytes)
7: {
8: unsafe
9: {
10: const int byte_len = 2; // 表示一个 byte 的字符长度。
11:
12: var str = new string('\0', byte_len * bytes.Length);
13:
14: fixed(char* pStr = str)
15: {
16: var pStr2 = pStr; // fixed pStr 是只读的,所以我们定义一个变量。
17:
18: foreach (var item in bytes)
19: {
20: *pStr2 = Digitals[item >> 4/* byte high */]; ++pStr2;
21: *pStr2 = Digitals[item & 15/* byte high */]; ++pStr2;
22: }
23: }
24:
25: return str;
26: }
27: }
28:
29: public static string ComputeHash<THashAlgorithm>(string input) where THashAlgorithm : HashAlgorithm
30: {
31: var instance = THashAlgorithmInstances<THashAlgorithm>.Instance; // 避免二次取值,微微提高效率(自我感觉)。
32: var encoding = Encoding.UTF8;
33:
34: // 我们在这里声明一个足量的 byte 数组,足以容下字符串的 utf-8 字节码和 hash 值的字节码。
35: var bytes = new byte[Encoding.UTF8.GetMaxByteCount(Math.Max(input.Length, instance.HashSize / 2))];
36:
37: var bytesCount = encoding.GetBytes(input, bytes);
38:
39: var source = new ReadOnlySpan<byte>(bytes, 0, bytesCount); // source: utf-8 bytes region.
40: var destination = new Span<byte>(bytes, bytesCount, bytes.Length - bytesCount); // destination: buffer region.
41:
42: if (bytes.Length - bytesCount > instance.HashSize && instance.TryComputeHash(source, destination, out var bytesWritten))
43: {
44: return ToString(destination.Slice(0, bytesWritten));
45: }
46: else
47: {
48: // 通常情况下这里就很有可能抛出异常了,但是我们封装工具方法必须有一个原则,我们尽量不要自行抛出。
49: // 用户的参数执行到这里我们依然调用 HashAlgorithm.ComputeHash,由它内部抛出异常。这样可以避免很多问题和歧义。
50: return ToString(instance.ComputeHash(bytes, 0, bytesCount));
51: }
52: }
53: }
我们再次测试,结果如下:
现在我们已经超官方示例达 5 倍了!这就是最终版本了。
最后附上各个版本实现的完整代码:
Core 2.1+ 包含不安全代码版本:
1: using System;
2: using System.Diagnostics;
3: using System.Reflection;
4: using System.Runtime.CompilerServices;
5: using System.Security.Cryptography;
6: using System.Text;
7:
8: static class THashAlgorithmInstances<THashAlgorithm> where THashAlgorithm : HashAlgorithm
9: {
10: /// <summary>
11: /// 线程静态变量。
12: /// 即:这个变量在每个线程中都是唯一的。
13: /// 再结合泛型类实现了该变量在不同泛型或不同的线程先的变量都是唯一的。
14: /// 这样做的目的是为了避开多线程问题。
15: /// </summary>
16: [ThreadStatic]
17: static THashAlgorithm instance;
18:
19: public static THashAlgorithm Instance => instance ?? Create();
20:
21: /// <summary>
22: /// 寻找 THashAlgorithm 类型下的 Create 静态方法,并执行它。
23: /// 如果没找到,则执行 Activator.CreateInstance 调用构造方法创建实例。
24: /// 如果 Activator.CreateInstance 方法执行失败,它会抛出异常。
25: /// </summary>
26: [MethodImpl(MethodImplOptions.NoInlining)]
27: static THashAlgorithm Create()
28: {
29: var createMethod = typeof(THashAlgorithm).GetMethod(
30: nameof(HashAlgorithm.Create), // 这段代码同 "Create",低版本 C# 可以替换掉
31: BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly,
32: Type.DefaultBinder,
33: Type.EmptyTypes,
34: null);
35:
36: if (createMethod != null)
37: {
38: instance = (THashAlgorithm)createMethod.Invoke(null, new object[] { });
39: }
40: else
41: {
42: instance = Activator.CreateInstance<THashAlgorithm>();
43: }
44:
45: return instance;
46: }
47: }
48:
49: public static class HashAlgorithmHelper
50: {
51: static readonly char[] Digitals = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
52:
53: static string ToString(ReadOnlySpan<byte> bytes)
54: {
55: unsafe
56: {
57: const int byte_len = 2; // 表示一个 byte 的字符长度。
58:
59: var str = new string('\0', byte_len * bytes.Length);
60:
61: fixed(char* pStr = str)
62: {
63: var pStr2 = pStr; // fixed pStr 是只读的,所以我们定义一个变量。
64:
65: foreach (var item in bytes)
66: {
67: *pStr2 = Digitals[item >> 4/* byte high */]; ++pStr2;
68: *pStr2 = Digitals[item & 15/* byte high */]; ++pStr2;
69: }
70: }
71:
72: return str;
73: }
74: }
75:
76: public static string ComputeHash<THashAlgorithm>(string input) where THashAlgorithm : HashAlgorithm
77: {
78: var instance = THashAlgorithmInstances<THashAlgorithm>.Instance;
79: var encoding = Encoding.UTF8;
80:
81: var bytes = new byte[Encoding.UTF8.GetMaxByteCount(Math.Max(input.Length, instance.HashSize / 2))];
82:
83: var bytesCount = encoding.GetBytes(input, bytes);
84:
85: var source = new ReadOnlySpan<byte>(bytes, 0, bytesCount); // source: utf-8 bytes region.
86: var destination = new Span<byte>(bytes, bytesCount, bytes.Length - bytesCount); // destination: buffer region.
87:
88: if (bytes.Length - bytesCount > instance.HashSize && instance.TryComputeHash(source, destination, out var bytesWritten))
89: {
90: return ToString(destination.Slice(0, bytesWritten));
91: }
92: else
93: {
94: return ToString(instance.ComputeHash(bytes, 0, bytesCount));
95: }
96: }
97: }
98:
99: class Program
100: {
101: public static string GetMd5Hash(string input)
102: {
103: using (MD5 md5Hash = MD5.Create())
104: {
105: // Convert the input string to a byte array and compute the hash.
106: byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
107:
108: // Create a new Stringbuilder to collect the bytes
109: // and create a string.
110: StringBuilder sBuilder = new StringBuilder();
111:
112: // Loop through each byte of the hashed data
113: // and format each one as a hexadecimal string.
114: for (int i = 0; i < data.Length; i++)
115: {
116: sBuilder.Append(data[i].ToString("x2"));
117: }
118:
119: // Return the hexadecimal string.
120: return sBuilder.ToString();
121: }
122: }
123:
124: static void Main(string[] args)
125: {
126: Console.WriteLine(HashAlgorithmHelper.ComputeHash<MD5>("Hello World!"));
127: Console.WriteLine(GetMd5Hash("Hello World!"));
128:
129: while (true)
130: {
131: var stopwatch = Stopwatch.StartNew();
132:
133: for (int i = 0; i < 1000000; i++)
134: {
135: HashAlgorithmHelper.ComputeHash<MD5>("Hello World!");
136: }
137:
138: Console.WriteLine(stopwatch.ElapsedMilliseconds);
139:
140: stopwatch = Stopwatch.StartNew();
141:
142: for (int i = 0; i < 1000000; i++)
143: {
144: GetMd5Hash("Hello World!");
145: }
146:
147: Console.WriteLine(stopwatch.ElapsedMilliseconds);
148: }
149: }
150: }
包含不安全代码的通用版本:
1: using System;
2: using System.Diagnostics;
3: using System.Reflection;
4: using System.Runtime.CompilerServices;
5: using System.Security.Cryptography;
6: using System.Text;
7:
8: static class THashAlgorithmInstances<THashAlgorithm> where THashAlgorithm : HashAlgorithm
9: {
10: /// <summary>
11: /// 线程静态变量。
12: /// 即:这个变量在每个线程中都是唯一的。
13: /// 再结合泛型类实现了该变量在不同泛型或不同的线程先的变量都是唯一的。
14: /// 这样做的目的是为了避开多线程问题。
15: /// </summary>
16: [ThreadStatic]
17: static THashAlgorithm instance;
18:
19: public static THashAlgorithm Instance => instance ?? Create();
20:
21: /// <summary>
22: /// 寻找 THashAlgorithm 类型下的 Create 静态方法,并执行它。
23: /// 如果没找到,则执行 Activator.CreateInstance 调用构造方法创建实例。
24: /// 如果 Activator.CreateInstance 方法执行失败,它会抛出异常。
25: /// </summary>
26: [MethodImpl(MethodImplOptions.NoInlining)]
27: static THashAlgorithm Create()
28: {
29: var createMethod = typeof(THashAlgorithm).GetMethod(
30: nameof(HashAlgorithm.Create), // 这段代码同 "Create",低版本 C# 可以替换掉
31: BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly,
32: Type.DefaultBinder,
33: Type.EmptyTypes,
34: null);
35:
36: if (createMethod != null)
37: {
38: instance = (THashAlgorithm)createMethod.Invoke(null, new object[] { });
39: }
40: else
41: {
42: instance = Activator.CreateInstance<THashAlgorithm>();
43: }
44:
45: return instance;
46: }
47: }
48:
49: public static class HashAlgorithmHelper
50: {
51: static readonly char[] Digitals = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
52:
53: static string ToString(byte[] bytes)
54: {
55: unsafe
56: {
57: const int byte_len = 2; // 表示一个 byte 的字符长度。
58:
59: var str = new string('\0', byte_len * bytes.Length);
60:
61: fixed(char* pStr = str)
62: {
63: var pStr2 = pStr; // fixed pStr 是只读的,所以我们定义一个变量。
64:
65: foreach (var item in bytes)
66: {
67: *pStr2 = Digitals[item >> 4/* byte high */]; ++pStr2;
68: *pStr2 = Digitals[item & 15/* byte high */]; ++pStr2;
69: }
70: }
71:
72: return str;
73: }
74: }
75:
76: public static string ComputeHash<THashAlgorithm>(string input) where THashAlgorithm : HashAlgorithm
77: {
78: var bytes = Encoding.UTF8.GetBytes(input);
79:
80: return ToString(THashAlgorithmInstances<THashAlgorithm>.Instance.ComputeHash(bytes));
81: }
82: }
83:
84: class Program
85: {
86: public static string GetMd5Hash(string input)
87: {
88: using (MD5 md5Hash = MD5.Create())
89: {
90: // Convert the input string to a byte array and compute the hash.
91: byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
92:
93: // Create a new Stringbuilder to collect the bytes
94: // and create a string.
95: StringBuilder sBuilder = new StringBuilder();
96:
97: // Loop through each byte of the hashed data
98: // and format each one as a hexadecimal string.
99: for (int i = 0; i < data.Length; i++)
100: {
101: sBuilder.Append(data[i].ToString("x2"));
102: }
103:
104: // Return the hexadecimal string.
105: return sBuilder.ToString();
106: }
107: }
108:
109: static void Main(string[] args)
110: {
111: Console.WriteLine(HashAlgorithmHelper.ComputeHash<MD5>("Hello World!"));
112: Console.WriteLine(GetMd5Hash("Hello World!"));
113:
114: while (true)
115: {
116: var stopwatch = Stopwatch.StartNew();
117:
118: for (int i = 0; i < 1000000; i++)
119: {
120: HashAlgorithmHelper.ComputeHash<MD5>("Hello World!");
121: }
122:
123: Console.WriteLine(stopwatch.ElapsedMilliseconds);
124:
125: stopwatch = Stopwatch.StartNew();
126:
127: for (int i = 0; i < 1000000; i++)
128: {
129: GetMd5Hash("Hello World!");
130: }
131:
132: Console.WriteLine(stopwatch.ElapsedMilliseconds);
133: }
134: }
135: }
不包含不安全代码的通用版本:
1: using System;
2: using System.Diagnostics;
3: using System.Reflection;
4: using System.Runtime.CompilerServices;
5: using System.Security.Cryptography;
6: using System.Text;
7:
8: static class THashAlgorithmInstances<THashAlgorithm> where THashAlgorithm : HashAlgorithm
9: {
10: /// <summary>
11: /// 线程静态变量。
12: /// 即:这个变量在每个线程中都是唯一的。
13: /// 再结合泛型类实现了该变量在不同泛型或不同的线程先的变量都是唯一的。
14: /// 这样做的目的是为了避开多线程问题。
15: /// </summary>
16: [ThreadStatic]
17: static THashAlgorithm instance;
18:
19: public static THashAlgorithm Instance => instance ?? Create();
20:
21: /// <summary>
22: /// 寻找 THashAlgorithm 类型下的 Create 静态方法,并执行它。
23: /// 如果没找到,则执行 Activator.CreateInstance 调用构造方法创建实例。
24: /// 如果 Activator.CreateInstance 方法执行失败,它会抛出异常。
25: /// </summary>
26: [MethodImpl(MethodImplOptions.NoInlining)]
27: static THashAlgorithm Create()
28: {
29: var createMethod = typeof(THashAlgorithm).GetMethod(
30: nameof(HashAlgorithm.Create), // 这段代码同 "Create",低版本 C# 可以替换掉
31: BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly,
32: Type.DefaultBinder,
33: Type.EmptyTypes,
34: null);
35:
36: if (createMethod != null)
37: {
38: instance = (THashAlgorithm)createMethod.Invoke(null, new object[] { });
39: }
40: else
41: {
42: instance = Activator.CreateInstance<THashAlgorithm>();
43: }
44:
45: return instance;
46: }
47: }
48:
49: public static class HashAlgorithmHelper
50: {
51: static readonly char[] Digitals = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
52:
53: static string ToString(byte[] bytes)
54: {
55: const int byte_len = 2; // 表示一个 byte 的字符长度。
56:
57: var chars = new char[byte_len * bytes.Length];
58:
59: var index = 0;
60:
61: foreach (var item in bytes)
62: {
63: chars[index] = Digitals[item >> 4/* byte high */]; ++index;
64: chars[index] = Digitals[item & 15/* byte high */]; ++index;
65: }
66:
67: return new string(chars);
68: }
69:
70: public static string ComputeHash<THashAlgorithm>(string input) where THashAlgorithm : HashAlgorithm
71: {
72: var bytes = Encoding.UTF8.GetBytes(input);
73:
74: return ToString(THashAlgorithmInstances<THashAlgorithm>.Instance.ComputeHash(bytes));
75: }
76: }
77:
78: class Program
79: {
80: public static string GetMd5Hash(string input)
81: {
82: using (MD5 md5Hash = MD5.Create())
83: {
84: // Convert the input string to a byte array and compute the hash.
85: byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
86:
87: // Create a new Stringbuilder to collect the bytes
88: // and create a string.
89: StringBuilder sBuilder = new StringBuilder();
90:
91: // Loop through each byte of the hashed data
92: // and format each one as a hexadecimal string.
93: for (int i = 0; i < data.Length; i++)
94: {
95: sBuilder.Append(data[i].ToString("x2"));
96: }
97:
98: // Return the hexadecimal string.
99: return sBuilder.ToString();
100: }
101: }
102:
103: static void Main(string[] args)
104: {
105: Console.WriteLine(HashAlgorithmHelper.ComputeHash<MD5>("Hello World!"));
106: Console.WriteLine(GetMd5Hash("Hello World!"));
107:
108: while (true)
109: {
110: var stopwatch = Stopwatch.StartNew();
111:
112: for (int i = 0; i < 1000000; i++)
113: {
114: HashAlgorithmHelper.ComputeHash<MD5>("Hello World!");
115: }
116:
117: Console.WriteLine(stopwatch.ElapsedMilliseconds);
118:
119: stopwatch = Stopwatch.StartNew();
120:
121: for (int i = 0; i < 1000000; i++)
122: {
123: GetMd5Hash("Hello World!");
124: }
125:
126: Console.WriteLine(stopwatch.ElapsedMilliseconds);
127: }
128: }
129: }
不包含不安全代码通用版本的性能:(性能依然极佳,建议使用此版本)