title: Fastest possible byte array concatenation method
body: <p>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:</p>
  
  <pre><code>public byte[] getMessageBytes() throws IOException {
      byte[] bytes = new byte[0];
      for (final Map.Entry&lt;Short,byte[]&gt; 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;
  }
  </code></pre>
  
  <p>And second one is using ByteArrayOutputStream:</p>
  
  <pre><code>public byte[] getMessageBytes() throws IOException {
      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      for (final Map.Entry&lt;Short,byte[]&gt; entry : myMap.entrySet()) {
          baos.write(entry.getValue());
      }
      baos.flush();
      return baos.toByteArray();
  }
  </code></pre>
  
  <p>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?</p>