java – 最快的字节数组连接方法
发布时间:2020-12-15 05:08:26 所属栏目:Java 来源:网络整理
导读:我得到一个包含消息的n部分的映射作为字节数组.在最后一篇文章进入地图后,必须连接消息.我找到了两个应该满足要求的解决方案.第一个是使用System.arraycopy: public byte[] getMessageBytes() throws IOException { byte[] bytes = new byte[0]; for (final
我得到一个包含消息的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,temp,bytes.length); System.arraycopy(entryBytes,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(); } 从性能和内存使用角度看,哪种方法更好? 解决方法
由于您可以通过累加片段的长度来找出消息的大小,我会:
>加上碎片的长度,并分配输出数组; 这可能是内存效率高且速度快的.但是,只有剖析才能说出完整的故事. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |