我得到了一個包含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;
}
而第二個是使用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();
}
什麼是從性能和內存使用的角度看到的更好的方法? 是否有另一種更好的連接方式?
你有沒有對這些進行基準測試,發現它們速度不夠快? – Poindexter
這真的是你的瓶頸嗎? – ControlAltDel
@Poindexter我發現如果地圖中有很多條目,這需要在洞過程中花費一些時間。所以我尋求改進。 – sebastian