We can reuse the MD5 instance. In fact, in .NET Core, it is already safe to reuse the MD5 instance.
In addition, we can change the hexadecimal conversion to a higher-performance Convert.ToHexString. The following are the results of the performance test, showing a 3-fold performance improvement:
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
for (int i = 0; i < 100; i++)
{
var str = $"abc{i}";
var staticNew = MD5Benchmark.Md5StaticNew(str);
var old = MD5Benchmark.Md5Old(str);
var @new = MD5Benchmark.Md5New(str);
Debug.Assert(old == @new);
Debug.Assert(old == staticNew);
}
[Orderer]
[MemoryDiagnoser]
public class MD5Benchmark
{
[Benchmark]
public void MD5Old()
{
_ = MD5Benchmark.Md5Old("Benchmark");
}
[Benchmark]
public void MD5New()
{
_ = MD5Benchmark.Md5New("Benchmark");
}
[Benchmark]
public void MD5StaticNew()
{
_ = MD5Benchmark.Md5StaticNew("Benchmark");
}
public static string Md5Old(string txt)
{
using (var md5 = MD5.Create())
{
var inputBytes = Encoding.ASCII.GetBytes(txt);
var hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
var sb = new StringBuilder();
for (var i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
public static string Md5New(string txt)
{
using var md5 = MD5.Create();
var inputBytes = Encoding.ASCII.GetBytes(txt);
var hashBytes = md5.ComputeHash(inputBytes);
return Convert.ToHexString(hashBytes);
}
private static readonly MD5 Md5 = MD5.Create();
public static string Md5StaticNew(string txt)
{
var inputBytes = Encoding.ASCII.GetBytes(txt);
var hashBytes = Md5.ComputeHash(inputBytes);
return Convert.ToHexString(hashBytes);
}
}
In this PR, two things have been done:
1.Standardize file names 2.Optimize MD5 performance
We can reuse the MD5 instance. In fact, in .NET Core, it is already safe to reuse the MD5 instance.
In addition, we can change the hexadecimal conversion to a higher-performance
Convert.ToHexString
. The following are the results of the performance test, showing a 3-fold performance improvement:Test Code: