最快的字节数组串联方法

seb*_*ian 3 java performance bytearray concatenation

我得到一个包含消息的n部分的映射作为字节数组.在最后一篇文章进入地图后,必须连接消息.我找到了两个应该满足要求的解决方案.第一个是使用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;
}
Run Code Online (Sandbox Code Playgroud)

第二个是使用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();
}
Run Code Online (Sandbox Code Playgroud)

从性能和内存使用角度看,哪种方法更好?是否有另一种方法可以进行更好的连接?

NPE*_*NPE 9

由于您可以通过累加片段的长度来找出消息的大小,我会:

  1. 加上碎片的长度,并分配输出数组;
  2. 使用循环将arraycopy()每个部分放入输出数组中的正确位置.

这可能是内存效率高且速度快的.但是,只有剖析才能说出完整的故事.