Java – the fastest byte array connection method

I get a mapping containing the N part of the message as a byte array After the last article enters the map, you must connect the message I found two solutions that should meet the requirements The first is to use 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,temp,bytes.length);
        System.arraycopy(entryBytes,bytes.length,entryBytes.length);
        bytes = temp;
    }
    return bytes;
}

The second is to use 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();
}

Which method is better in terms of performance and memory usage? Is there another way to connect better?

Solution

Since you can find the size of the message by accumulating the length of the fragment, I will:

>Add the length of the fragment and allocate the output array; > Use a loop to put each part of arraycopy () in the correct position in the output array

This may be memory efficient and fast However, only analysis can tell a complete story

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>