Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this code slow?

I have the following code which is used to encode byte array to HEX string

private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
public static void WriteHexBytes(byte[] data, StringBuilder sb)
{
    char[] chars = new char[data.length*2];
    for (int i = 0; i < data.length; ++i)
    {
        chars[2*i] = HEX_CHARS[(data[i] & 0xF0) >>> 4];
        chars[2*i + 1] = HEX_CHARS[data[i] & 0x0F];
    }
    sb.append(chars);
}

The for loop is very slow, it takes about 10 seconds to encode 3MB of bytes on real device. On the emulator it takes like forever. The sb.append is performed instantly.

Is this normal? It seems very slow to me? What is causing slowness?

Tested on Samsung Galaxy Tab 2 7.0

like image 790
Dusan Avatar asked May 14 '26 08:05

Dusan


1 Answers

It's not obvious that there is a faster approach than what you show, from a Java perspective. Apache Common's code looks slightly better than yours, but that's really just a vague guess.

From here on, if you need more, you'll just have to Microbenchmark on your hardware, I'm afraid :(.

Just out of idleness … I did micro benchmark (ad-hoc, unscientific) your solution and one I just cooked up -- you win by a factor of two. Here's what I tried:

public static void niko(byte[] data, StringBuilder sb)
{
    for (byte element : data) {
        sb.append(toChar((element & 0xf0) >>> 4));
        sb.append(toChar(element & 0x0f));
    }
}

static char toChar(int b) {
    int offset = b < 10 ? 48 : 87;
    return (char) (b + offset);
}

Going thru 10 MB 100 times, your code completes in 4 seconds, mine in 8. But keep in mind that this is very hardware dependent, JVM-dependenect, etc.

like image 57
nes1983 Avatar answered May 15 '26 20:05

nes1983



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!