From 9c49fce4ffb5aa16d36e21988f7af0b6d68a6265 Mon Sep 17 00:00:00 2001 From: irodai-majom <181323284+irodai-majom@users.noreply.github.com> Date: Wed, 30 Oct 2024 15:50:42 +0100 Subject: [PATCH] Optimized HexToBytes function (#469) - used Span - used Convert.FromHexString vectorized function --- src/N_m3u8DL-RE.Common/Util/HexUtil.cs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/N_m3u8DL-RE.Common/Util/HexUtil.cs b/src/N_m3u8DL-RE.Common/Util/HexUtil.cs index 20944d9..d20c636 100644 --- a/src/N_m3u8DL-RE.Common/Util/HexUtil.cs +++ b/src/N_m3u8DL-RE.Common/Util/HexUtil.cs @@ -34,15 +34,13 @@ namespace N_m3u8DL_RE.Common.Util public static byte[] HexToBytes(string hex) { - hex = hex.Trim(); - if (hex.StartsWith("0x") || hex.StartsWith("0X")) - hex = hex.Substring(2); - byte[] bytes = new byte[hex.Length / 2]; + var hexSpan = hex.AsSpan().Trim(); + if (hexSpan.StartsWith("0x") || hexSpan.StartsWith("0X")) + { + hexSpan = hexSpan.Slice(2); + } - for (int i = 0; i < hex.Length; i += 2) - bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); - - return bytes; + return Convert.FromHexString(hexSpan); } } }