Java性能中的Hex到String太慢了

Pip*_*ith 8 java performance android hex ascii

我的android程序有以下方法,用Java编写.

该方法接受一个十六进制字符串,并返回以ascii编写的相同文本的字符串.

public static String hexToString(String hex)
{
    StringBuilder sb = new StringBuilder();

    for (int count = 0; count < hex.length() - 1; count += 2)
    {
        String output = hex.substring(count, (count + 2));    //grab the hex in pairs

        int decimal = Integer.parseInt(output, 16);    //convert hex to decimal

        sb.append((char)decimal);    //convert the decimal to character
    }

    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)

该方法工作正常,但我的程序非常关键,这种方法可能被称为成千上万次.在分析程序的慢速位时,由于以下原因,此方法占用了太多时间:

Integer.parseInt(output, 16);
Run Code Online (Sandbox Code Playgroud)

hex.substring(count, (count + 2));
Run Code Online (Sandbox Code Playgroud)

以最慢的顺序排在第一位.

有谁知道更快的方法来实现同样的事情?

Lui*_*oza 8

不要在每次迭代时创建新的String.提高性能的一种方法是使用char数组并对每个字符应用数学运算.

public static String hexToString(String hex) {
    StringBuilder sb = new StringBuilder();
    char[] hexData = hex.toCharArray();
    for (int count = 0; count < hexData.length - 1; count += 2) {
        int firstDigit = Character.digit(hexData[count], 16);
        int lastDigit = Character.digit(hexData[count + 1], 16);
        int decimal = firstDigit * 16 + lastDigit;
        sb.append((char)decimal);
    }
    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)

有关此方法的更多信息:

此外,如果您要成对解析十六进制字符串,则可以使用查找表,因为@ L7ColWinters建议:

private static final Map<String, Character> lookupHex = new HashMap<String, Character>();

static {
    for(int i = 0; i < 256; i++) {
        String key = Integer.toHexString(i);
        Character value = (char)(Integer.parseInt(key, 16));
        lookupHex.put(key, value);
    }
}

public static String hexToString(String hex) {
    StringBuilder sb = new StringBuilder();
    for (int count = 0; count < hex.length() - 1; count += 2) {
        String output = hex.substring(count, (count + 2));
        sb.append((char)lookupHex.get(output));
    }
    return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)