Maar als je bv een wachtwoord met MD5 (of welke andere hashing methode dan ook) genereert wil je juist dat je wat trager bentThomasG schreef op dinsdag 21 mei 2013 @ 12:57:
Ik werd toch even nieuwsgierig naar de performance van verschillende manieren om een string om te zetten naar MD5. Ik heb drie implementaties genomen, en ToMD5_3 is het snelste. Bij 1.000.000 iteraties, op een i7-2600k:
ToMD5_1: 7075ms ToMD5_2: 6300ms ToMD5_3: 5752ms
C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 using System; using System.Diagnostics; using System.Security.Cryptography; using System.Text; namespace ConsoleApplication1 { static class StringExtensions { public static string ToMD5_1(this string value) { StringBuilder hexadecimal = new StringBuilder(); using (MD5 md5Hash = MD5.Create()) { byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(value)); for (int i = 0; i < data.Length; i++) hexadecimal.Append(data[i].ToString("x2")); } return hexadecimal.ToString().ToLower(); } public static string ToMD5_2(this string value) { byte[] data; using (MD5 md5 = MD5.Create()) { data = md5.ComputeHash(Encoding.UTF8.GetBytes(value)); } return BitConverter.ToString(data).ToLower().Replace("-", string.Empty); } public static string ToMD5_3(this string value) { byte[] data; using (MD5 md5 = MD5.Create()) { data = md5.ComputeHash(Encoding.UTF8.GetBytes(value)); } return data.ToHex().ToLower(); } } static class ByteExtensions { private const string hexChars = "0123456789ABCDEF"; public static string ToHex(this byte[] bytes) { int length = bytes.Length * 2; char[] hex = new char[length]; int byteIndex = 0; for (int charIndex = 0; charIndex < length; charIndex += 2) { byte byteValue = bytes[byteIndex++]; hex[charIndex] = hexChars[byteValue / 16]; hex[charIndex + 1] = hexChars[byteValue % 16]; } return new string(hex); } } class Program { static void Main(string[] args) { int iterations = 1000000; Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { "thisisasillystringtodosomemagicon".ToMD5_1(); } sw.Stop(); Console.WriteLine((sw.ElapsedMilliseconds).ToString()); sw = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { "thisisasillystringtodosomemagicon".ToMD5_2(); } sw.Stop(); Console.WriteLine((sw.ElapsedMilliseconds).ToString()); sw = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { "thisisasillystringtodosomemagicon".ToMD5_3(); } sw.Stop(); Console.WriteLine((sw.ElapsedMilliseconds).ToString()); Console.ReadLine(); } } }
