Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
sebastian Avatar asked Sep 08 '26 12:09

sebastian


1 Answers

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.

like image 178
NPE Avatar answered Sep 11 '26 01:09

NPE



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!