VB.net 的性能损失相当于从十六进制到字节的轻量级转换

Performance loss in VB.net equivalent of light weight conversion from hex to byte

我已经通读了这里的答案

我也尝试生成等效的 VB.net 代码:

Option Strict ON

Public Function ParseHex(hexString As String) As Byte()
    If (hexString.Length And 1) <> 0 Then
        Throw New ArgumentException("Input must have even number of characters")
    End If
    Dim length As Integer = hexString.Length \ 2
    Dim ret(length - 1) As Byte
    Dim i As Integer = 0
    Dim j As Integer = 0
    Do While i < length
        Dim high As Integer = ParseNybble(hexString.Chars(j))
        j += 1
        Dim low As Integer = ParseNybble(hexString.Chars(j))
        j += 1
        ret(i) = CByte((high << 4) Or low)
        i += 1
    Loop

    Return ret
End Function

Private Function ParseNybble(c As Char) As Integer
    If c >= "0"C AndAlso c <= "9"C Then
        Return c - "0"C
    End If
    c = ChrW(c And Not &H20)
    If c >= "A"C AndAlso c <= "F"C Then
        Return c - ("A"C - 10)
    End If
    Throw New ArgumentException("Invalid nybble: " & c)
End Function

我们可以在不引入数据转换的情况下消除 ParseNybble 中的编译错误吗?

Return c - "0"c 运算符 '-' 没有为类型 'Char' 和 'Char'

定义

c = ChrW(c And Not &H20) 运算符 'And' 没有为类型 'Char' 和 'Integer'

定义

按照目前的情况,没有。

但是,您可以将 ParseNybble 更改为采用整数并将 AscW(hexString.Chars(j)) 传递给它,以便数据转换发生在 ParseNybble 之外。

这个解决方案比我尝试过的所有替代方案都要快得多。它避免了任何 ParseNybble 查找。

Function hex2byte(s As String) As Byte()
    Dim l = s.Length \ 2
    Dim hi, lo As Integer
    Dim b(l - 1) As Byte

    For i = 0 To l - 1
        hi = AscW(s(i + i))
        lo = AscW(s(i + i + 1))

        hi = (hi And 15) + ((hi And 64) >> 6) * 9
        lo = (lo And 15) + ((lo And 64) >> 6) * 9

        b(i) = CByte((hi << 4) Or lo)
    Next

    Return b
End Function