Search code examples
javaperformancearraysconcatenation

Fastest possible byte array concatenation method


I got a map containing n parts of a message as a byte array. After the last piece has found his way into the map, the message has to be concatenated. I found two solutions which should meet the requirements. First one is using System.arraycopy:

public byte[] getMessageBytes() throws IOException {
    byte[] bytes = new byte[0];
    for (final Map.Entry<Short,byte[]> entry : myMap.entrySet()) {
        byte[] entryBytes = entry.getValue();
        byte[] temp = new byte[bytes.length + entryBytes.length];
        System.arraycopy(bytes, 0, temp, 0, bytes.length);
        System.arraycopy(entryBytes, 0, temp, bytes.length, entryBytes.length);
        bytes = temp;
    }
    return bytes;
}

And second one is using ByteArrayOutputStream:

public byte[] getMessageBytes() throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (final Map.Entry<Short,byte[]> entry : myMap.entrySet()) {
        baos.write(entry.getValue());
    }
    baos.flush();
    return baos.toByteArray();
}

What is the better method seen from the angle of performance and memory usage? Is there an alternative way of doing the concatenation which is even better?


Solution

  • Since you can find out the size of the message by adding up the lengths of the pieces, I would:

    1. add up the lengths of the pieces, and allocate the output array;
    2. use a loop to arraycopy() each piece into the correct position in the output array.

    This is likely to be memory-efficient and fast. However, only profiling can tell the full story.