This is an automated email from the ASF dual-hosted git repository. lizhanhui pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/rocketmq-clients.git
The following commit(s) were added to refs/heads/master by this push: new 79fcd013 Optimize the performance of the Hash algorithm and reduce allocations. (#690) 79fcd013 is described below commit 79fcd013109cd9f02f3b81639566e737b612f164 Author: InCerryGit <36690780+incerry...@users.noreply.github.com> AuthorDate: Mon Apr 1 14:20:49 2024 +0800 Optimize the performance of the Hash algorithm and reduce allocations. (#690) --- csharp/rocketmq-client-csharp/Utilities.cs | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/csharp/rocketmq-client-csharp/Utilities.cs b/csharp/rocketmq-client-csharp/Utilities.cs index 331d8a40..831ab835 100644 --- a/csharp/rocketmq-client-csharp/Utilities.cs +++ b/csharp/rocketmq-client-csharp/Utilities.cs @@ -34,6 +34,8 @@ namespace Org.Apache.Rocketmq private static readonly string HostName = System.Net.Dns.GetHostName(); private static readonly byte[] RandomMacAddressBytes = Enumerable.Range(0, 6).Select(_ => (byte)new Random().Next(256)).ToArray(); + private static readonly ThreadLocal<MD5> Md5 = new ThreadLocal<MD5>(MD5.Create); + private static readonly ThreadLocal<SHA1> Sha1 = new ThreadLocal<SHA1>(SHA1.Create); public const int MasterBrokerId = 0; @@ -80,24 +82,31 @@ namespace Org.Apache.Rocketmq return $"{hostName}@{pid}@{index}@{no}"; } +#if NET5_0_OR_GREATER public static string ComputeMd5Hash(byte[] data) { - using (var md5 = MD5.Create()) - { - var hashBytes = md5.ComputeHash(data); - return BitConverter.ToString(hashBytes).Replace("-", ""); - } + var hashBytes = Md5.Value.ComputeHash(data); + return Convert.ToHexString(hashBytes); } public static string ComputeSha1Hash(byte[] data) { - using (var sha1 = SHA1.Create()) - { - var hashBytes = sha1.ComputeHash(data); - return BitConverter.ToString(hashBytes).Replace("-", ""); - } + var hashBytes = Sha1.Value.ComputeHash(data); + return Convert.ToHexString(hashBytes); + } +#else + public static string ComputeMd5Hash(byte[] data) + { + var hashBytes = Md5.Value.ComputeHash(data); + return BitConverter.ToString(hashBytes).Replace("-", ""); } + public static string ComputeSha1Hash(byte[] data) + { + var hashBytes = Sha1.Value.ComputeHash(data); + return BitConverter.ToString(hashBytes).Replace("-", ""); + } +#endif private static string DecimalToBase36(long decimalNumber) {