简体   繁体   English

Java:将ByteBuffer复制到byte []数组是否对性能没有影响?

[英]Java: Is copying a ByteBuffer to a byte[] array a performance no-no?

Basically, my situation is this: 基本上,我的情况是这样的:

  1. Server streams data from the client connection to a ByteBuffer object called inQueue . 服务器将数据从客户端连接流式传输到称为inQueueByteBuffer对象。 This contains whatever the most recent stream of data is 它包含最新的数据流
  2. Server must process the data in each of these streams and expect a packet of data in a specific format 服务器必须处理每个流中的数据,并期望使用特定格式的数据包
  3. The payload of data is to be read into a byte[] object then processed separately 数据的有效载荷将被读取到byte[]对象中,然后分别进行处理

Now my question boils down to this: is copying the remaining buffer data (the payload) to a byte[] array bad for performance? 现在我的问题归结为: 将剩余的缓冲区数据(有效负载)复制到对性能不利的byte[]数组上吗?

Here's what it would look like: 如下所示:

// pretend we're reading the packet ID and length
// int len = LENGTH OF PACKET PAYLOAD

/* 
 * Mark the starting position of the packet's payload.
 */
int pos = inQueue.position();

byte[] payload = new byte[len];
inQueue.get(payload);

// Process the packet's payload here

/*
 * Set the inQueue buffer to the length added to the previous position
 * so as to move onto the next packet to process.
 */
inQueue.position(pos + len);

As you can see, I'm essentially doing this: 如您所见,我基本上是在这样做:

  1. Mark the position of the complete buffer as it were just before the payload 将完整缓冲区的位置标记为正好在有效负载之前
  2. Copy the contents of inQueue as far as the payload goes to a separate byte[] object 复制inQueue的内容,直到有效负载转到单独的byte[]对象
  3. Set the complete buffer's position to after the payload we just read so we can read more packets 将完整缓冲区的位置设置为我们刚刚读取的有效负载之后,以便我们可以读取更多数据包

My concern is that, in doing this, I'm wasting memory by copying the buffer. 我担心的是,这样做会通过复制缓冲区浪费内存。 Keep in mind the packets used will never exceed 500 bytes and are often under 100 bytes . 请记住,所使用的数据包永远不会超过500个字节,并且经常会少于100个字节

Is my concern valid, or am I being performance-paranoid? 我的担忧是否有效,或者我表现得偏执? :p :p

You should avoid it. 你应该避免它。 That's the whole reason for the ByteBuffer design: to avoid data copies. 这就是ByteBuffer设计的全部原因:避免数据复制。

What exactly do you mean by 'process payload here'? “在这里处理有效负载”到底是什么意思?

With a little rearrangement of whatever happens in there, you should be able to do that directly in the ByteBuffer, calling flip() first, one or more get() s to get the data you require, and compact() afterwards ( clear() if you're sure it's empty), without an intermediate copy step into yet another byte[] array. 稍作重新排列,您应该能够直接在ByteBuffer中做到这一点,首先调用flip() ,再调用一个或多个get()来获取所需的数据,然后再调用compact()clear()如果您确定它为空),则无需中间复制即可将其复制到另一个byte []数组中。

这不仅是不必要的,而且要回答您的问题,没有,即使扩大规模,您也不会注意到性能变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM